我正在使用pyodbc查询到SQL Server数据库
import datetime import pyodbc conn = pyodbc.connect("Driver={SQL Server};Server='dbserver',Database='db', TrustedConnection=Yes") cursor = conn.cursor() ratings = ("PG-13", "PG", "G") st_dt = datetime(2010, 1, 1) end_dt = datetime(2010, 12, 31) cursor.execute("""Select title, director, producer From movies Where rating In ? And release_dt Between ? And ?""", ratings, str(st_dt), str(end_dt))
但收到以下错误。元组参数是否需要以其他方式处理?有没有更好的方法来构造此查询?
('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Line 9: Incorrect syntax near '@P1'. (170) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server] Statement(s) could not be prepared. (8180)")
更新:
我能够使用字符串格式运算符来使该查询正常工作,因为引入了安全性考虑,所以这不是理想的选择。
import datetime import pyodbc conn = pyodbc.connect("Driver={SQL Server};Server='dbserver',Database='db', TrustedConnection=Yes") cursor = conn.cursor() ratings = ("PG-13", "PG", "G") st_dt = datetime(2010, 1, 1) end_dt = datetime(2010, 12, 31) cursor.execute("""Select title, director, producer From movies Where rating In %s And release_dt Between '%s' And '%s'""" % (ratings, st_dt, end_dt))
您不能IN ()使用单个字符串参数在子句中参数化多个值。实现此目的的唯一方法是:
IN ()
字符串替换(如您所做的那样)。
以表单形式构建参数化查询,IN (?, ?, . . ., ?)然后为每个占位符传递一个 单独的 参数。我不是Python到ODBC的专家,但是我认为使用Python这样的语言来做这件事特别容易。这比较安全,因为您可以获得参数化的全部价值。
IN (?, ?, . . ., ?)