How to use variables to execute SQL statements in Python
P粉725827686
2023-08-21 16:40:37
<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 without having Python make them part of the query text? </p>
Different Python DB-API implementations allow different placeholders, so you need to find out which one you are using -- for example (using MySQLdb):
Or (using sqlite3 from the Python standard library):
or other methods (after
VALUES
, you can use(:1, :2, :3)
, or use "named styles"(:fee, :fie, :fo)
or(%(fee)s, %(fie)s, %(fo)s)
, in which case you need to use a dictionary as the second parameters are passed to theexecute
function). Check theparamstyle
string constants in the DB API module you are using, and look at paramstyle at http://www.python.org/dev/peps/pep-0249/ , understand all the parameter passing methods!Please note that the parameters are 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