Question
Asked By – user111606
I have the following Python code:
cursor.execute("INSERT INTO table VALUES var1, var2, var3,")
where var1
is an integer, var2
and var3
are strings.
How can I write the variable names without Python including them as part of the query text?
Now we will see solution for issue: How to use variables in SQL statement in Python?
Answer
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
Note that the parameters are passed as a tuple.
The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%
), because
- it does not do any escaping or quoting.
- it is prone to Uncontrolled string format attacks e.g. SQL injection.
This question is answered By – Ayman Hourieh
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0