如何使用 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.