简体   繁体   English

Python cx_Oracle 中 Oracle Prepared Statement 的 IN 子句

[英]IN clause for Oracle Prepared Statement in Python cx_Oracle

I'd like to use the IN clause with a prepared Oracle statement using cx_Oracle in Python.我想在 Python 中使用 cx_Oracle 将 IN 子句与准备好的 Oracle 语句一起使用。

Eg query - select name from employee where id in ('101', '102', '103')例如查询 - select name from employee where id in ('101', '102', '103')

On python side, I have a list [101, 102, 103] which I converted to a string like this ('101', '102', '103') and used the following code in python -在 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()

This doesn't work.这是行不通的。 Am I doing something wrong?难道我做错了什么?

This concept is not supported by Oracle -- and you are definitely not the first person to try this approach either! Oracle 不支持此概念——您也绝对不是第一个尝试此方法的人! You must either:您必须:

  • create separate bind variables for each in value -- something that is fairly easy and straightforward to do in Python为每个值创建单独的绑定变量——这在 Python 中是相当容易和直接的
  • create a subquery using the cast operator on Oracle types as is shown in this post: https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:210612357425使用 Oracle 类型的强制转换运算符创建子查询,如本文所示: https : //asktom.oracle.com/pls/asktom/f?p=100 :11:0 :::: p11_question_id: 210612357425

  • use a stored procedure to accept the array and perform multiple queries directly within PL/SQL使用存储过程接受数组并直接在 PL/SQL 中执行多个查询

  • or do something else entirely!或者完全做其他事情!

Otra opción es dar formato a una cadena con la consulta. 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()

Just transform your list into a tuple and format the sql string with it只需将您的列表转换为元组并用它格式化 sql 字符串

ids = [101, 102, 103]
param = tuple(ids)
results = cursor.execute("select name from employee where id IN {}".format(param))

Since you created the string, you're almost there.自从你创建了字符串,你就快到了。 This should work:这应该有效:

results = cursor.execute('select name from employee where id in ' + ALL_IDS)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM