How to use variables in SQL statements in Python?
P粉200138510
2023-08-20 17:35:10
<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>
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):
Or (using sqlite3 from the Python standard library):
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 ofexecute
dictionary rather than a map). Check theparamstyle
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!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