0

我想用python写一个sql openquery。我写的普通sql查询如下:

sql_query = select name from emp where id= %s 

我正在执行它: cursor.execute(sql_query, (id_value,))

它运作良好。

但是,现在我有一个类似的 openquery:

sql_query = select * from openquery([LS], 'select name from \"DB\"."view" where \"id\" Like %s') 

如果我执行:cursor.execute(sql_query, (id_value,))

我会收到一条错误消息:

SQL 包含 0 个参数标记,但提供了 1 个参数。

我知道这个错误即将到来,因为 %s 是在单引号查询中指定的。但是我不能删除那个单引号,因为在 SQL Server 本身中没有它,查询就无法工作。

我尝试使用以下方式运行查询:

cursor.execute(sql_query % (id_value))

它有效。但我不想使用这个,因为这种格式容易出现 SQL 注入。

那么,如何在 python 中编写一个安全的参数化 openquery。

4

1 回答 1

0

请在“id_value”之后的参数块中删除多余的逗号(“,”):

sql_query = select * from openquery([LS], 'select name from \"DB\"."view" where \"id\" Like %s')    

cursor.execute(sql_query, (id_value))
于 2020-01-27T10:09:55.227 回答