如何使用 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 (?, ?, ?)'

当你调用执行时,它会按正确方式用转义值替换占位符。

更新于:05-03-2020

2K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.