How to use variables in SQL statement in Python?
好吧,所以我在Python方面没那么有经验。
我有以下python代码:
1 | cursor.execute("INSERT INTO table VALUES var1, var2, var3,") |
其中
如何在不使用python的情况下编写变量名,并将它们作为查询文本的一部分?
1 | cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3)) |
请注意,参数作为元组传递。
数据库API正确地转义和引用变量。注意不要使用字符串格式运算符(
允许不同的python db-api实现使用不同的占位符,因此您需要找出正在使用的占位符——它可能是(例如,使用mysqldb):
1 | cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3)) |
或者(例如,使用python标准库中的sqlite3):
1 | cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3)) |
或者其他(在
很多方法。不要在真正的代码中使用最明显的(
从sqlite3的pydoc复制粘贴:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # Never do this -- insecure! symbol = 'RHAT' c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol) # Do this instead t = ('RHAT',) c.execute('SELECT * FROM stocks WHERE symbol=?', t) print c.fetchone() # Larger example that inserts many records at a time purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ] c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases) |
如果您需要更多示例:
1 2 3 4 5 6 7 8 9 10 | # Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) |
网址:http://www.amk.ca/python/writing/db-api.html
当您简单地将变量值附加到语句中时要小心:想象一下一个自称为
1 2 | cursor.execute("insert into Attendees values (?, ?, ?)", (name, seminar, paid) ) |