我正在尝试定义值列表(id号)并将它们传递给查询Oracle表的SQL。
只要我只包含一个id,此代码就可以正常工作。
named_params = {'ids':'123456548'}
query = """
select PEBEMPL_ECLS_CODE
from PEBEMPL
inner join SPRIDEN on spriden_pidm = pebempl_pidm
where SPRIDEN_CHANGE_IND is null
and SPRIDEN_ID in :ids
"""
df = pd.read_sql(query, connection, params=named_params)
执行相同但传递id列表的正确语法是什么?
例如,此代码不起作用:
idlist = ['123456548','546465464']
named_params = {'ids':idlist}
query = """
select PEBEMPL_ECLS_CODE
from PEBEMPL
inner join SPRIDEN on spriden_pidm = pebempl_pidm
where SPRIDEN_CHANGE_IND is null
and SPRIDEN_ID in :ids
"""
df = pd.read_sql(query, connection, params=named_params)
错误返回:
': ORA-01484: arrays can only be bound to PL/SQL statements
答案 0 :(得分:2)
您需要为列表中的每个项目创建单独的绑定参数,然后将ID列表传递到read_sql()
:
idlist = ['123456548','546465464']
in_vars = ','.join(':%d' % i for i in range(len(idlist)))
query = """
select PEBEMPL_ECLS_CODE
from PEBEMPL
inner join SPRIDEN on spriden_pidm = pebempl_pidm
where SPRIDEN_CHANGE_IND is null
and SPRIDEN_ID in (%s)
""" % in_vars
df = pd.read_sql(query, connection, params=idlist)
为避免混淆,上面的示例使用Pandas read_sql()
函数与Oracle进行对话。对于直接使用cursor
对象的人,语法为:
cursor.execute(query, params)
答案 1 :(得分:0)
我相信你必须将参数作为字符串传递。可以使用逗号加入要查询的所有ID,并将其作为字符串发送到SPRIDEN_ID。