How to use variables in SQL statement in Python?

前端 未结 4 1119
后悔当初
后悔当初 2020-11-21 05:36

Ok so I\'m not that experienced in Python.

I have the following Python code:

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


        
4条回答
  •  礼貌的吻别
    2020-11-21 06:00

    Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):

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

    or (e.g. with sqlite3 from the Python standard library):

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

    or others yet (after VALUES you could have (:1, :2, :3) , or "named styles" (:fee, :fie, :fo) or (%(fee)s, %(fie)s, %(fo)s) where you pass a dict instead of a map as the second argument to execute). Check the paramstyle string constant in the DB API module you're using, and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ to see what all the parameter-passing styles are!

提交回复
热议问题