[英]How can I pass parameters to `cursor.execute` in `pymssql`?
I am connecting to sql server db via pymssql
library. 我正在通过
pymssql
库连接到sql server db。 And I am trying to use the method cursor.execute(sql, params)
to execute query. 而且我正在尝试使用
cursor.execute(sql, params)
来执行查询。
sql = """
SELECT
MIN(myDate)
FROM
%s
"""
The sql statement is defined above. 上面定义了sql语句。 It simply selects the minimum date value from the table.
它只是从表中选择最小日期值。
when I run below code to pass the parameter: 当我运行以下代码以传递参数时:
cursor.execute(sql, 'Daily')
I got this error pymssql.ProgrammingError: (102, b"Incorrect syntax near 'Daily'.DB-Lib error message 20018, severity 15:\\nGeneral SQL Server error: Check messages from the SQL Server\\n")
. 我收到此错误
pymssql.ProgrammingError: (102, b"Incorrect syntax near 'Daily'.DB-Lib error message 20018, severity 15:\\nGeneral SQL Server error: Check messages from the SQL Server\\n")
。
I wonder how the parameter should be passed to the sql statement? 我想知道如何将参数传递给sql语句?
After some debugging I found the issue relates to the table name. 经过一些调试后,我发现问题与表名有关。 It looks like I can't put table name in the parameter.
看来我无法在参数中添加表名称。 The reason I don't want to concentrate the sql string is to avoid sql injection.
我不想集中sql字符串的原因是为了避免sql注入。 Is there a way to pass the table name as a parameter?
有没有办法将表名作为参数传递?
try this 尝试这个
sql = 'SELECT MIN(myDate) FROM %s'
cursor.execute(sql , ['Daily'])
May be your query is including \\n
. 可能是您的查询包含
\\n
。
Repalce \\n
with space( ' '
) 用空格(
' '
代替\\n
Try this, 尝试这个,
sql = """
SELECT
MIN(myDate)
FROM
%s
"""
cursor.execute(sql.replace('\n',' '), ('Daily',))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.