1

I have the following query:

SOUTHERN_STATE = ["AL", "GA", "TN", ....]

query = """
    SELECT
        *
    FROM
        USERS
    WHERE
        STATE in ({})
""".format(SOUTHERN_STATE)

but I got this error: ORA00936: missing expression

How can I use a list in an Oracle query in Python?

2

2 Answers 2

7

The answer supplied by Joe Thor will work well so long as the values in the SOUTHERN_STATE variable are well-known and cannot result in SQL injection. If the values are not well-known, this solution can be used instead:

SOUTHERN_STATE = ["AL", "GA", "TN", ....]
bind_names = ",".join(":" + str(i + 1) for i in range(len(SOUTHERN_STATE)))
sql = f"""
    SELECT *
    FROM USERS
    WHERE STATE in ({bind_names})"""
for row in cursor.execute(query, SOUTHERN_STATE):
    print(row)

You can see more details about this approach in the cx_Oracle user documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

That's using python format strings rather than cx_oracle bind parameters and would be unsafe if any of the values came from input.
Nope, its using bind variables. Note the colon (:) in tthe bind names!
0

Join the python list into a string and pass the string. Per the comments, using the logic in this post:

Python cx_Oracle module: unable to format query in code


SOUTHERN_STATE = ["AL", "GA", "TN", ....]
SOUTHERN_STATE_STRING ','.join(['%s'] * len(SOUTHERN_STATE))


query = """
    SELECT
        *
    FROM
        USERS
    WHERE
        STATE in ({})
""".format(SOUTHERN_STATE_STRING, tuple(SOUTHERN_STATE))

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.