Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable values dynamically in pandas sql query

How to pass variable parameters dynamically

order = 10100

status = 'Shipped'

df1 = pd.read_sql_query("SELECT  * from orders where orderNumber =""" +  
str(10100) + """ and status = """ + 'status' +"""  order by orderNumber """,cnx)

TypeError: must be str, not int

getting above error although i converted to strings any idea?

is there any alternative wy to pass the parameters?

like image 875
Kumar AK Avatar asked Feb 05 '18 18:02

Kumar AK


1 Answers

Use parametrized sql by supplying the arguments via the params keyword argument. The proper quotation of arguments will be done for you by the database adapter and the code will be less vulnerable to SQL injection attacks. (See Little Bobby Tables for an example of the kind of trouble improperly quoted, non-parametrized sql can get you into.)

order = 10100

status = 'Shipped'

sql = """SELECT  * from orders where orderNumber = ?
         and status = ? order by orderNumber"""
df1 = pd.read_sql_query(sql, cnx, params=[order, status])

The ?s in sql are parameter markers. They get replaced with properly quoted values from params. Note that the proper parameter marker depends on the database adapter you are using. For example, MySQLdb and psycopg2 uses %s, while sqlite3, and oursql uses ?.

like image 172
unutbu Avatar answered Oct 22 '22 09:10

unutbu