Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically bind multiple parameters on SQL query in python?

So, I've a table (say table_name ) and it columns are:

|  A   |  B   |  C   |
------------------------
|  a1  |  b1  |  c1  |
|  a2  |  b2  |  c2  |
   ...

Now i have to read a column data using following query:

import pandas as pd
import pymysql as pycon

con = pycon.connect(host='localhost',user='root',password='', db='database')

#Error in here
df= pd.read_sql_query("SELECT A from table_name where B = %s and C != %s" %variableB %variableC, con)

But I've encountered an error in read_sql_query(...) maybe the query format is wrong because dynamically binded single parameter works fine i.e

df= pd.read_sql_query("SELECT A from table_name where B = %s" %variableB, con)

works w/o error. Can anyone help me with the query?

like image 973
realpac Avatar asked Mar 05 '26 22:03

realpac


2 Answers

In case someone ran into same problem, the correct code for query was with a '%s' instead of %s

df= pd.read_sql_query("SELECT A from table_name where B = '%s' and C != '%s'" % (variableB, variableC), con)

the code below gave me pymysql.err.InternalError.

df= pd.read_sql_query("SELECT A from table_name where B = %s and C != %s" % (variableB, variableC), con)

Thank you stackOverflow :)

like image 77
realpac Avatar answered Mar 08 '26 12:03

realpac


when you bind your multiple variable into String, syntax should be like this

df= pd.read_sql_query("SELECT A from table_name where B = %s and C != %s" % (variableB, variableC), con)
like image 25
Wonjin Avatar answered Mar 08 '26 12:03

Wonjin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!