Home  >  Q&A  >  body text

How to use variables in SQL statements in Python?

<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粉200138510P粉200138510426 days ago473

reply all(2)I'll reply

  • P粉545682500

    P粉5456825002023-08-21 13:22:44

    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!

    reply
    0
  • P粉926174288

    P粉9261742882023-08-21 10:38:41

    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.

    reply
    0
  • Cancelreply