SQLite实际上从未将参数替换为SQL查询字符串本身;参数的值在执行命令时直接读取.
(格式化这些值只是为了将它们再次解析为相同的值,这将是无用的开销.)
但是如果你想知道如何在SQL中编写参数,你可以使用quote function;像这样的东西:
def log_and_execute(cursor, sql, *args):
s = sql
if len(args) > 0:
# generates SELECT quote(?), quote(?), ...
cursor.execute("SELECT " + ", ".join(["quote(?)" for i in args]), args)
quoted_values = cursor.fetchone()
for quoted_value in quoted_values:
s = s.replace('?', quoted_value, 1)
print "SQL command: " + s
cursor.execute(sql, args)
(如果有一个?不是参数,那么此代码将失败,即在文字字符串中.)