6

I'm trying to define a list of values (id numbers) and pass them to SQL that's querying Oracle tables.

This code works as long as I only include one 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)

What's the correct syntax for doing the same but passing a list of ids?

This code, for example, doesn't work:

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)

Error Returned:

': ORA-01484: arrays can only be bound to PL/SQL statements

2 Answers 2

9

You will need to create a separate bind parameter for each item in the list, and then pass the list of ids into 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)

To avoid any confusion, the above example talks to Oracle using Pandas read_sql() function. For people working with a cursor object directly, then the syntax is:

cursor.execute(query, params)
Sign up to request clarification or add additional context in comments.

3 Comments

I get the following error with this code: "ORA-01008: not all variables bound". Any suggestion?
Sorry my mistake - the idlist should be passed as a keyword argument - as params=idlist. I have updated the answer.
just for completeness' sake: link to the relevant cx_oracle documenation
0

I believe you will have to pass the parameters as string. May be join all the ID's you want to query with a comma and send it as a string to SPRIDEN_ID.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.