0

I am attempting to run a SQL query on an oracle database like so:

import cx_Oracle as cx
import pandas as pd

un = "my username"
pw = "my password"
db = "database name"
lookup = "1232DX%"

myconn = cx.connect(un, pw, db)
cursor = myconn.cursor()

qry = """SELECT *
    FROM tableX
    WHERE tableX.code LIKE '1232DX%'"""

qry.df = pd.read_sql(qry, con = myconn)
myconn.close()

My issue is that it is redundant to define lookup before the query and use the value in the query itself. I would like to just be able to type

WHERE tableX.code LIKE lookup

and have the value 1232DX% substituted into my query.

I imagine there is a straightforward way to do this in Python, but I am hardly an expert so I thought I would ask someone here. All suggestions are welcome. If there is a better way to do this than what I have shown please include it. Thank you in advance.

1 Answer 1

3

You use the same syntax as when passing parameters to cursor.execute().

qry = """SELECT *
    FROM tableX
    WHERE tableX.code LIKE :pattern"""
qry.df = pd.read_sql(qry, con = myconn, params={":pattern": lookup})
Sign up to request clarification or add additional context in comments.

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.