How to use variables in SQL statement in Python? Ask Question

How to use variables in SQL statement in Python? Ask Question

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?

ベストアンサー1

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

Note that the parameters are passed as a tuple, (a, b, c). If you're passing a single parameter, the tuple needs to end with a comma, (a,).

The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%), because

  1. It does not do any escaping or quoting.
  2. It is prone to uncontrolled string format attacks e.g. SQL injection.

おすすめ記事