This question already has answers here:
How to use variables in SQL statement in Python?
(5 answers)
Closed 1 year ago.
I want the SQL term to search for the ID that has been given by the user as input.
def autoAusgeben():
autoID = int(input("Id des Autos eingeben: "))
connection = sqlite3.connect("quartett.db")
cursor = connection.cursor()
cursor.execute("SELECT * From autos WHERE Id (?)", (autoID))
autos = cursor.fetchall()
print(autos)
If autoID is defined earlier in code, then I believe you may be receiving some kind of "undefined function 'Id' in expression error" due to missing = sign? Does changing that line to this help?
cursor.execute("SELECT * From autos WHERE Id = (?)", (autoID))
After adding to missing "=" it gives the error "parameters are of unsopported type".
autoID has never been used before.
EDIT:
ive added a "," behind autoID in braces
Works now
Thx
Related
This question already has answers here:
SQLite INSERT - ON DUPLICATE KEY UPDATE (UPSERT)
(5 answers)
Closed 6 months ago.
Im having a problem with my sqlite database in my python program. I'm trying to create a table that will hold records of players score. Player name is saved as variable "val" and that variable is used in sql code. Also if the player is already in my table I don't want to create duplicate.
My problem is that if I don't use WHERE {v}... it all works, but the moment i try to prevent table from creating duplicates it gives me an OperationalError: near "WHERE": syntax error.
Im quite new to sql so it's hard for me to find what i'm doing wrong. I used (?) and format and as long as i don't use WHERE it's fine. How can I make sure that my variable (player name) from outside of sql code is not in my table so i can insert it?
val = "PlayerName"
cur.execute( """
INSERT INTO Table (player_name)
VALUES {v}
WHERE {v} NOT IN (
SELECT player_name FROM Table)""".format(v = val))
Ok, it works now. My main problem was that i tried to use commands from MySQL instead of sqlite. My code that worked:
cur.execute( """INSERT INTO Table (player_name)
VALUES (?)
ON CONFLICT(player_name) DO UPDATE SET player_name= player_name""",(val) )
Edit: Final version without player_name = player_name workaround:
cur.execute( """INSERT OR IGNORE INTO Table (player_name) VALUES (?)""",(val) )
This question already has answers here:
How to create a "singleton" tuple with only one element
(4 answers)
Closed 3 years ago.
I have the following code and it works, but I need to understand why there is a comma after the variable id_to_remove, can someone explain to me why that has to be there? (I bolded the part I don't understand)
def delete_user(id_to_remove):
sql = "DELETE FROM USERS WHERE ID = ?"
conn = create_connection()
cursor = conn.cursor()
**cursor.execute(sql, (id_to_remove, ))**
conn.commit()
conn.close()
So I don't know why its id_to_remove, and not just cursor.execute(sql,(id_to_remove))
Because it will replace all the ? values with the ones in the tuple. If you don't put a comma then it is a single value, you need to add it to construct a single value tuple.
This question already has answers here:
Python sqlite3 string variable in execute
(3 answers)
Closed 4 years ago.
Basiclly I wish to use a string I have saved in a python variable as my parameter 'table-name' in "PRAGMA table_info(table-name);"
import sqlite3
connect = sqlite3.connect('exampleDB.sqlite')
cur = connect.cursor()
x = 'a string'
cur.execute("PRAGMA table_info(?)", (x,))
This was my first idea. Which did not work and neither did:
cur.execute("PRAGMA table_info(table) VALUES (?)", (x,))
Which was an idea I got from here.
Just putting the variable in there like so:
cur.execute("PRAGMA table_info(x))
also proved fruitless.
Any ideas? This is my first time posting here so feel free to lecture me on how or where I should have posted this differently should you see fit.
Try this
cur.execute("PRAGMA table_info({})".format(x))
You want to do the following:
cur.execute("PRAGMA table_info(" + x + ")")
Note, this is a duplicate of Python sqlite3 string variable in execute
This question already has an answer here:
How do I use SQL parameters with python?
(1 answer)
Closed 5 years ago.
I am trying to create a SQL query in a python program and I want to pass in my session variable. The session variable contains the logged in user for the program. I am having some syntax issues.
query = "SELECT * FROM following WHERE following.username == 'flask.session['user']' "
Here is my error:
sqlite3.OperationalError: near "user": syntax error
I am not sure how to fix this. Help would be greatly appreciated.
roganjosh fixed the issue.
Use:
cursor.execute("SELECT * FROM following WHERE username = ?", (flask.session['user'],))
If you know that session['user'] is a string, than try this:
query = "SELECT * FROM following WHERE following.username == '%s' " %(session['user'])
You can use, %s for string, %i for integer...
This question already has answers here:
Sqlite syntax error even though there's no syntax error. Help?
(2 answers)
Closed 6 years ago.
I currently have a sqlite statement that looks like this in the debugger
'SELECT id FROM ITable where question=\\'Is your child\\'s serial correct?\\''
this is the code
def TestStatement(question,patient_id,student_id):
try:
str = "SELECT id FROM ITable where question='%s' " %(question)
r = executeSelect(str) #<<--------Exception occurs here
except Exception as e:
return "Exception Occured"
return r
The question parameter is:
'Is your child\\'s serial correct?'
The exception returned is:
near "s": syntax error
I cannot modify the question parameter. Any suggestions on what I might be doing wrong ? or why this sql statement is incorrect ?
The problem is - you are using string formatting to construct your query - this not only dangerous (see SQL injections), but also leads to problems with Python-to-database type conversions and quotes (which is exactly what you have in this case).
Instead, omit the quotes and use a parameterized query:
query = "SELECT id FROM ITable where question = ?"
cursor.execute(query, (question, ))
Note: you would probably need to adjust your executeSelect() function to accept parameters in separate argument(s).