Python cx_Oracle 中 Oracle 准备语句的 IN 子句
IN clause for Oracle Prepared Statement in Python cx_Oracle
我想将 IN 子句与使用 Python 中的 cx_Oracle 的准备好的 Oracle 语句一起使用。
例如查询 - select name from employee where id in ('101', '102', '103')
在 python 方面,我有一个列表 [101, 102, 103]
,我将其转换为这样的字符串 ('101', '102', '103')
并在 python - [=16] 中使用了以下代码=]
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 不支持此概念 -- 您也绝对不是第一个尝试此方法的人!您必须:
- 为每个值创建单独的绑定变量——这在 Python
中相当容易和直接
在 Oracle 类型上使用强制转换运算符创建一个子查询,如此 post 所示:https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:210612357425
使用存储过程接受数组,直接在PL/SQL
内进行多次查询
或者完全做其他事情!
自从您创建字符串后,您就快完成了。这应该有效:
results = cursor.execute('select name from employee where id in ' + ALL_IDS)
另一种选择是使用查询格式化字符串。
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()
我想将 IN 子句与使用 Python 中的 cx_Oracle 的准备好的 Oracle 语句一起使用。
例如查询 - select name from employee where id in ('101', '102', '103')
在 python 方面,我有一个列表 [101, 102, 103]
,我将其转换为这样的字符串 ('101', '102', '103')
并在 python - [=16] 中使用了以下代码=]
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 不支持此概念 -- 您也绝对不是第一个尝试此方法的人!您必须:
- 为每个值创建单独的绑定变量——这在 Python 中相当容易和直接
在 Oracle 类型上使用强制转换运算符创建一个子查询,如此 post 所示:https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:210612357425
使用存储过程接受数组,直接在PL/SQL
内进行多次查询
或者完全做其他事情!
自从您创建字符串后,您就快完成了。这应该有效:
results = cursor.execute('select name from employee where id in ' + ALL_IDS)
另一种选择是使用查询格式化字符串。
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()