Python 在需要手动构造查询的情况下,如何使用查询参数?
我使用的是Python 2,代码如下:Python 在需要手动构造查询的情况下,如何使用查询参数?,python,sql,Python,Sql,我使用的是Python 2,代码如下: with conn.cursor() as cursor: info("Updating {} records".format(len(records_to_update))) for record in records_to_update: query = "UPDATE my_table SET " params_setters = [] # Process all fields exce
with conn.cursor() as cursor:
info("Updating {} records".format(len(records_to_update)))
for record in records_to_update:
query = "UPDATE my_table SET "
params_setters = []
# Process all fields except wsid when updating
for index, header in enumerate(DB_COLUMNS_IN_ORDER[1:]):
if record[index] is not None:
params_setters.append("{} = '{}' ".format(header, record[index]))
query += " , ".join(params_setters)
query += " WHERE id = '{}'".format(record[0])
cursor.execute(query)
如何在此处使用查询参数进行转义,而不必在以下位置手动转义:
params_setters.append("{} = '{}' ".format(header, record[index]))
如果我理解你的问题,你要用事先准备好的陈述。如果您使用的驱动程序使用
%s
表示查询参数(SQLite使用?
),则:
您正在使用哪个数据库?@Talon Postgres
with conn.cursor() as cursor:
info("Updating {} records".format(len(records_to_update)))
params = []
for record in records_to_update:
query = "UPDATE my_table SET "
params_setters = []
# Process all fields except wsid when updating
for index, header in enumerate(DB_COLUMNS_IN_ORDER[1:]):
if record[index] is not None:
params_setters.append("{} = %s ".format(header))
params.append(record[index])
query += " , ".join(params_setters)
query += " WHERE id = %s"
params.append(record[0])
cursor.execute(query, params)