如何使用 Python 元组编写 SQL IN 查询?


要编写 SQL IN 查询,你需要确保使用  在查询中提供占位符,以便正确转义查询。例如,

示例

my_tuple = ("Hello", "world", "John")
placeholder= '?'
placeholders= ', '.join(placeholder for _ in my_tuple)
query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
print(query)

# 现在使用游标执行

cursor.execute(query, my_tuple)

输出

将给出输出

'SELECT name FROM students WHERE id IN (?, ?, ?)'

当你调用执行时,它将用转义值正确地替换这些占位符。

更新于:2020-03-05

2K+ 次浏览

开启你的职业生涯

完成课程获取认证

开始
广告
© . All rights reserved.