![](/img/trans.png)
[英]pymssql/pyodbc performance (cursor.execute) is very slow when querying large SQL Server table
[英]Using cursor.execute arguments in pymssql with IN sql statement
我有麻烦使用一个简单的SQL语句与运算符IN通过pymssql。
这是一个示例:
import pymssql
conn = pymssql.connect(server='myserver', database='mydb')
cursor = conn.cursor()
req = "SELECT * FROM t1 where id in (%s)"
cursor.execute(req, tuple(range(1,10)))
res = cursor.fetchall()
令人惊讶的是,只返回了第一个id,我无法弄清楚原因。 有没有人遇到同样的行为?
您正在尝试将九个ID值传递给查询,并且您只有一个占位符。 这样做可以获得九个占位符:
ids = range(1,10)
placeholders = ','.join('%s' for i in ids)
req = "SELECT * FROM t1 where id in ({})".format(placeholders)
cursor.execute(req, ids)
res = cursor.fetchall()
顺便说一句,你不一定需要一个元组。 列表将正常工作。
看起来你只传递SELECT * FROM t1 where id in (1)
。 您使用元组调用execute
,但字符串只有一个格式化程序。 要传递所有值,请像这样调用execute
:
cursor.execute(req, (tuple(range(1,10)),))
这会将元组作为第一个参数传递给要格式化的字符串。
编辑:关于executeone/many()
事情,如果你调用executemany
并返回last而不是第一个id,似乎execute
将运行查询10次,因为它可以格式化10个值的字符串。 最后一次运行将返回最后一个id。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.