How to use variables in SQL statements in Python?
P粉200138510
P粉200138510 2023-08-20 17:35:10
0
2
521
<p>I have the following Python code: </p> <pre class="brush:py;toolbar:false;">cursor.execute("INSERT INTO table VALUES var1, var2, var3,") </pre> <p>Where <code>var1</code> is an integer, <code>var2</code> and <code>var3</code> are strings. </p> <p>How do I write variable names in Python without them being included in the query text? </p>
P粉200138510
P粉200138510

reply all(2)
P粉545682500

Different implementations of the Python DB-API allow different placeholders, so you need to find out which one you are using -- for example (using MySQLdb):

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

Or (using sqlite3 from the Python standard library):

cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3))

or something else (after VALUES you can have (:1, :2, :3), or "named style" (:fee, :fie , :fo) or (%(fee)s, %(fie)s, %(fo)s), pass one in the second parameter of execute dictionary rather than a map). Check the paramstyle string constants in the DB API module you are using and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ , to learn about all parameter passing styles!

P粉926174288
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

Please note that the parameter is passed as a tuple, (a, b, c). If you pass only one parameter, the tuple needs to end with a comma, (a,).

The database API will properly escape and quote variables. Please be careful not to use the string formatting operator (%) because

  1. It does not do any escaping or quoting.
  2. It is vulnerable to uncontrollable string formatting attacks, such as SQL injection.
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template