realpac
realpac

Reputation: 572

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?

Upvotes: 3

Views: 9674

Answers (2)

realpac
realpac

Reputation: 572

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 :)

Upvotes: 3

Wonjin
Wonjin

Reputation: 432

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)

Upvotes: 1

Related Questions