我在通过 pymssql 使用带有运算符 IN 的简单 sql 语句时遇到问题。
这是一个示例:
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()
顺便说一句,您在这里不一定需要元组。一个列表就可以了。
关于python - 在带有 IN sql 语句的 pymssql 中使用 cursor.execute 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32384458/