[英]IN clause for Oracle Prepared Statement in Python cx_Oracle
我想在 Python 中使用 cx_Oracle 將 IN 子句與准備好的 Oracle 語句一起使用。
例如查詢 - select name from employee where id in ('101', '102', '103')
在 python 端,我有一個列表[101, 102, 103]
,我將其轉換為這樣的字符串('101', '102', '103')
並在 python 中使用了以下代碼 -
import cx_Oracle
ids = [101, 102, 103]
ALL_IDS = "('{0}')".format("','".join(map(str, ids)))
conn = cx_Oracle.connect('username', 'pass', 'schema')
cursor = conn.cursor()
results = cursor.execute('select name from employee where id in :id_list', id_list=ALL_IDS)
names = [x[0] for x in cursor.description]
rows = results.fetchall()
這是行不通的。 難道我做錯了什么?
Oracle 不支持此概念——您也絕對不是第一個嘗試此方法的人! 您必須:
使用 Oracle 類型的強制轉換運算符創建子查詢,如本文所示: https : //asktom.oracle.com/pls/asktom/f?p=100 :11:0 :::: p11_question_id: 210612357425
使用存儲過程接受數組並直接在 PL/SQL 中執行多個查詢
或者完全做其他事情!
Otra opción es dar formato a una cadena con la Consulta。
import cx_Oracle
ids = [101, 102, 103]
ALL_IDS = "('{0}')".format("','".join(map(str, ids)))
conn = cx_Oracle.connect('username', 'pass', 'schema')
cursor = conn.cursor()
query = """
select name from employee where id in ('{}')
""".format("','".join(map(str, ids)))
results = cursor.execute(query)
names = [x[0] for x in cursor.description]
rows = results.fetchall()
只需將您的列表轉換為元組並用它格式化 sql 字符串
ids = [101, 102, 103]
param = tuple(ids)
results = cursor.execute("select name from employee where id IN {}".format(param))
自從你創建了字符串,你就快到了。 這應該有效:
results = cursor.execute('select name from employee where id in ' + ALL_IDS)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.