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...
Related
This question already has answers here:
How to use variables in SQL statement in Python?
(5 answers)
Closed 4 months ago.
I want to run the following code, but Python gives me an error
code :
select = input("ENTER USER FOR PASS RECOVERY : ")
cursor.execute("SELECT COUNT(*) FROM user_stat WHERE usr=(%s)",(select))
python code
error :
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1
error picture
In which part of the code is the problem and what should I do?
The second argument to cursor.execute must be an iterable of params, So you should pass them as:
A list: [select]
A tuple: (select, ). Note that passing (select) does not make it a tuple.
And another question, which client do you use to connect to MySQL? Some clients use ? as param placeholders and not %s
if you need more examples or more help similar post is here -> How to use variables in SQL statement in Python?
Also take a look at Kashyap (https://stackoverflow.com/a/21734918/2561174) comment with a good/bad query practices, he give this example on how to use it:
# Do this instead
t = ('RHAT',)
cur.execute('SELECT * FROM stocks WHERE symbol=?', t)
Wish it helps you!
You have to use {} instead of ()
select = input("ENTER USER FOR PASS RECOVERY : ")
cursor.execute("SELECT COUNT(*) FROM user_stat WHERE usr={%s}",(select))
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
This question already has answers here:
How to use variables in SQL statement in Python?
(5 answers)
Closed 2 years ago.
I'm quite a beginner to SQL so I'm probably missing something import, but I'll ask anyway:
I'm creating a login program using an SQL database in python using SQLite3. When trying to check if a security question is correct I use these lines of code:
py_Username = input()
Answer1 = input()
if Answer1 == Cursor.execute("SELECT Security_Question1 FROM UserInfo WHERE Username = " + py_Username):
When doing this I get this error and don't know why...
Traceback (most recent call last):
if Answer1 == Cursor.execute("SELECT Security_Question1 FROM UserInfo WHERE Username = " + py_Username):
sqlite3.OperationalError: no such column: jake9
Please Help! Thanks.
You are checking the value Answer1 with the return value Cursor.execute() function which is wrong.
Note that to access the tuple data you need to use Cursor.fetchall() and then iterate through it. Try experimenting with the following code and refer the documentation.
```lang-python```
records = Cursor.execute("Statement")
for row in records:
print(row)
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).
This question already has an answer here:
Is this Python code vulnerable to SQL injection? (SQLite3)
(1 answer)
Closed 9 years ago.
I'm starting to program a Python application that works with databases. Reading about prepared statements, I found how I'm supposed to write them:
...
strSQL = "select * from myTable where aField = $s" % (aValue)
cursor.execute(strSQL)
...
My question is: Isn't this vulnerable to SQL injection? If so, how can I prevent it?
Thank you
You are using the string formatting operator instead of bound SQL parameters, so your code is indeed at risk of SQL injection (once you fix the $s, which I take to be a typo).
The correct form is:
strSQL = "select * from myTable where aField = %s"
cursor.execute(strSQL, [aValue])
The way you have it, absolutely! Here's how you would "help" get around the sql injection
strSQL = "select * from myTable where aField = %s"
cursor.execute(strSQL, [aValue])
Pass the values as a list/tuple to the second argument on the cursor execute