如何将参数化的sql查询放入变量中,然后在Python中执行?

How to put parameterized sql query into variable and then execute in Python?

提问人:Will 提问时间:10/28/2009 更新时间:11/1/2021 访问量:51999

问:

我知道在 Python 中格式化 sql 查询的正确方法是这样的:

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

这样就可以防止SQL注入。我的问题是,是否有办法将查询放在变量中然后执行它?我已经尝试了以下示例,但收到错误。可以这样做吗?

sql="INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3
cursor.execute(sql)
蟒蛇 SQL

评论


答:

6赞 Ants Aasma 10/28/2009 #1

你已经很接近了。

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

星号表示该变量不应被视为一个参数,而是解压缩为多个参数。

评论

0赞 bzupnick 4/4/2016
你为什么用而不是?例如,要执行此操作:,%sql_and_params = "INSERT INTO table VALUES (%s, %s, %s)" % (var1, var2, var3)
2赞 Eric Hughes 5/25/2016
@bzupnick使用简单的字符串格式(运算符)或替换可能会允许 SQL 注入,更不用说在需要时无法向文本添加引号了。参数化查询比格式化/替换查询要好得多。%
25赞 unutbu 10/28/2009 #2

以下是 cursor.execute 的调用签名:

Definition: cursor.execute(self, query, args=None)

    query -- string, query to execute on server
    args -- optional sequence or mapping, parameters to use with query.

所以 execute 最多需要 3 个参数(args 是可选的)。 如果给出 args,则它应该是一个序列。 所以

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

是行不通的,因为

cursor.execute(*sql_and_params)

将元组sql_and_params扩展为 4 个参数(同样,execute 仅期望 3 个参数)。

如果你真的必须使用

sql_and_params = "INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3

然后,在喂食时,您必须将其分解:cursor.execute

cursor.execute(sql_and_params[0],sql_and_params[1:])

但我认为只使用两个变量感觉更愉快:

sql = "INSERT INTO table VALUES (%s, %s, %s)"
args= var1, var2, var3
cursor.execute(sql, args)
1赞 Joe Rivera 8/8/2020 #3

这对我有用。使用 pyodbc 查询 Microsoft SQL Server。

cusotmer_list = ['ABC', '123']

# parameterized query placeholders
placeholders = ",".join("?" * len(customer_list))

# query table
query = 
"""
SELECT
[ID],
[Customer]
FROM xyz.dbo.abc
WHERE [Customer] IN (%s)
""" % placeholders

# read query results in pandas dataframe
df = pd.read_sql(sql=query, con=cnxn, params=customer_list)
1赞 Morteza Parvaresh 10/31/2021 #4

在 Python 中将参数传递给 SQL 查询的最佳方法是:

"INSERT INTO table VALUES (:1, :2, :3)  ", [val1, val2, val3]

或另一个例子:

"UPDATE table T SET T.column2 = :1 where T.column1= :2 ", [val1,val2]