The main problem I am having is inserting the correct word id from one table to another based on the word the user had to guess.
cursor.execute (f"SELECT word_ID FROM WORDS WHERE word = puzzle_to_solve (SELECT puzzle_to_solve FROM WORDS WHERE word = puzzle_to_solve)")
conn.commit()
player_ID = cursor.lastrowid
statistics = (player_ID, word_ID, score)
cursor.execute (f"INSERT INTO STATISTICS ('{player_ID}', '{word_ID}', {score}) VALUES (?, ?, ?)", statistics)
conn.commit()
I expect the output to insert the correct player id, word id and score into the table in my database. The player id and score part of the query does work.
The error I am receiving is mentioned below:
sqlite3.OperationalError: near "SELECT": syntax error
This error is appearing in the select statement line of code.
update your query to this:
cursor.execute (f"SELECT word_ID, player_ID FROM WORDS WHERE word = puzzle_to_solve")
conn.commit()
Related
I have a table Employee in SQL Server as follows:
ID (AUTO, PK),
firstname (varchar),
lastname (varchar)
I want to insert data like ('John', 'Myers') into the table.
I used the following code in Python using pyodbc:
connection = pyodbc.connect(...)
cursor = connection.cursor()
cursor.execute("insert into employee(firstname, lastname) values(?, ?)", ['John','Myers'])
Is it possible to get the ID value of this newly inserted row without having to write a select query?
You can use the OUTPUT clause
cursor.execute("insert into employee(firstname, lastname) output inserted.ID values(?, ?);", ['John','Myers'])
id = cursor.fetchone()
Alternatively, use SCOPE_IDENTITY()
cursor.execute("insert into employee(firstname, lastname) values(?, ?); select SCOPE_IDENTITY();", ['John','Myers'])
id = cursor.fetchone()
import csv
import sqlite3
open("shows.db", "w").close()
con = sqlite3.connect('shows.db')
db = con.cursor()
db.execute("CREATE TABLE shows (id INTEGER, title TEXT, PRIMARY KEY(id))")
db.execute("CREATE TABLE genres (show_id INTEGER, genre TEXT, FOREIGN KEY(show_id) REFERENCES shows(id))")
with open("/Users/xxx/Downloads/CS50 2019 - Lecture 7 - Favorite TV Shows (Responses) - Form Responses 1.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
title = row["title"].strip().upper()
id = db.execute("INSERT INTO shows (title) VALUES(?)", (title,))
for genre in row["genres"].split(", "):
db.execute("INSERT INTO genres (show_id, genre) VALUES(?, ?)", id,genre)
con.commit()
con.close()
When I run this code I think in this line "db.execute("INSERT INTO genres (show_id, genre) VALUES(?, ?)", id,genre)" the problem happens.
My console says
"db.execute("INSERT INTO genres (show_id, genre) VALUES(?, ?)", id,genre)
TypeError: function takes at most 2 arguments (3 given)"
I don't under stand why it says 3 given even though I gave two argument ( id, genre )
enter image description here
Problems with code
This line returns the cursor. In order to get the result, you will need to call terminal operations such as .fetchall(), .fetchmany() or .fetchone()
id = db.execute("INSERT INTO shows (title) VALUES(?)", (title,))
As you didn't call the terminal operator or print out the result, you wouldn't know that the INSERT operation returns None, not actual id
Minor: generally, it isn't advised to call variables the same name as built-in Python functions. See id.
As I suggested in the comment, you will need to insert a tuple:
db.execute(
"INSERT INTO genres (show_id, genre) VALUES (?, ?)",
(id_, genre)
)
Solution
You will need to select title from the shows table after insertion. Also, retrieve the id from the selection and then insert it into the genres table.
The simplified version of the code, to showcase how to do it:
import csv
import sqlite3
open("shows.db", "w").close()
con = sqlite3.connect('shows.db')
db = con.cursor()
db.execute("CREATE TABLE shows (id INTEGER, title TEXT, PRIMARY KEY(id))")
db.execute("CREATE TABLE genres (show_id INTEGER, genre TEXT, FOREIGN KEY(show_id) REFERENCES shows(id))")
shows = ["FRIENS", "Game of Trhones", "Want", "Scooby Doo"]
genres = ["Comedy", "Fantasy", "Action", "Cartoon"]
for ind, show in enumerate(shows):
db.execute("INSERT INTO shows (title) VALUES(?)", (show,))
id_ = con.execute(
"SELECT id FROM shows WHERE title = :show ORDER BY id DESC LIMIT 1",
{
"show": show
},
).fetchone()
db.execute(
"INSERT INTO genres (show_id, genre) VALUES (?, ?)",
(id_[0], genres[ind], )
)
con.commit()
con.close()
For more details, check my code on the GitHub.
SELECT statement may look a bit complex. What it does in a nutshell, it takes the matching title and returns the largest id. As titles may be the same, you always take the last inserted that matches.
General suggestions on debugging issues like that
Try using print as much as possible
Use dir and type functions to see methods and be able to google types
Search docs or examples on GitHub
I can see your issue. It's because you're trying the add in the id and genre into the query like they do in the sqlite3 documentation. In the documentation they did what your trying to do in a tuple but you did it in the function call.
Try this instead:
sql_query = ("INSERT INTO genres (show_id, genre) VALUES(?, ?)", id, genre)
db.execute(sql_query)
Or you could put it into a one-liner:
# notice how there is 2 parenthesis
# ↓ ↓
db.execute(("INSERT INTO genres (show_id, genre) VALUES(?, ?)", id, genre))
# ↑ ↑
I'm trying to insert data into sql table like this
conn = sqlite3.connect('Tags.db')
cur = conn.cursor()
input = open('word_freq_list.txt', 'r', encoding = 'UTF-8')
for word in input.read().split():
p = morph.parse(word)[0]
pos = p.tag.POS
case = p.tag.case
num = p.tag.number
gender = p.tag.gender
cur.execute(''' INSERT INTO Words_with_tags (POS, CASE, NUM, GENDER)
VALUES (?, ?, ?, ?)''', (pos, case, num, gender))
conn.commit()
But every I'm getting an error message:
sqlite3.OperationalError: near "CASE": syntax error
I can't understand why: column names are placed in the right order, the names are right too.
CASE is a Reserved Word, you can't use it as a column or variable name in your SQL query. Try using another column name instead of CASE.
my python program isn't working properly and it's something with the submit button and it gives me an error saying:
TypeError: 'str' object is not callable
help please. Here is the part of the code that doesn't work:
def submit():
g_name = ent0.get()
g_surname = ent1.get()
g_dob = ent2.get()
g_tutorg = ent3.get() #Gets all the entry boxes
g_email = ent4.get()
cursor = db.cursor()
sql = '''INSERT into Students, (g_name, g_surname, g_dob, g_tutorg, g_email) VALUES (?,?,?,?,?)'''
cursor.execute(sql (g_name, g_surname, g_dob, g_tutorg, g_email))
#Puts it all on to SQL
db.commit()
mlabe2=Label(mGui,text="Form submitted, press exit to exit").place(x=90,y=0)
I'm not sure what else you need so here's the rest of the SQL part that creates the table
cursor = db.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS Students(
StudentID integer,
Name text,
Surname text,
DOB blob,
Tutor_Grop blob,
Email blob,
Primary Key(StudentID));
""") #Will create if it doesn't exist
db.commit()
I've been trying so long and couldn't find a solution to this problem so if you can help that would be great thanks
problem maybe in your line:
cursor.execute(sql (g_name, g_surname, g_dob, g_tutorg, g_email))
try change it like this:
cursor.execute(sql, (g_name, g_surname, g_dob, g_tutorg, g_email))
Edit:
I call SQLite inserts in my simple app with this code:
data = (None, spath, sfile, sfilename, sha256hash, )
cur.execute("INSERT INTO filesoid VALUES (?, ?, ?, ?, ?)", data)
and it works ok.
You're not passing the values for your variables correctly. The way you've called cursor.execute(sql()) makes the interpreter think it's a function.
You need to format the sql string correctly:
sql = '''INSERT into Students, ({}, {}, {}, {}, {}) VALUES (?,?,?,?,?)'''.format(g_name, g_surname, g_dob, g_tutorg, g_email)
then use:
cursor.execute(sql)
EDIT:
or you may need to pass a tuple with data:
sql = '''INSERT into Students VALUES (?,?,?,?,?)'''
'data = (g_name, g_surname, g_dob, g_tutorg, g_email)
and then use
cursor.execute(sql, data)'
It depends on what those values actually are, and without seeing the database, I can't tell.
I have made a function which counts the amount of rows there are in a table using the cursor.rowcountfunction in Python. Now I want to apply that to tables I choose through %s. The problem is that I don't know how to apply it. Here is the sample I am working with.
def data_input (table):
cursor.execute ("USE database")
cursor.execute ("TRUNCATE TABLE table1")
cursor.execute ("TRUNCATE TABLE table2")
cursor.execute ("LOAD DATA LOCAL INFILE 'table1data' INTO TABLE table1 FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n' (field1, field2, field3, field4, field5)")
cursor.execute ("LOAD DATA LOCAL INFILE 'table2data' INTO TABLE table2 FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n' (field1, field2, field3)")
cursor.execute ("SELECT * FROM %s", table)
print cursor.rowcount
data_input ("table1")
Basically what it already does is input all the data into tables in MySQL from a text file, now I want the function to also print the number of rows for a particular table. It is getting an error message saying wrong MySQL syntax so this code is wrong for the rowcount part.
query = "SELECT COUNT(*) from `%s`" %table
cursor.execute(query) #execute query separately
res = cursor.fetchone()
total_rows = res[0] #total rows