Search code examples
pythonsqlpandaspymysql

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?


Solution

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