Search code examples
python-3.xpandasql

python: How to pass parameter into SQL query


I have a function with a parameter. This parameter must be replaced in a SQL query and then execute it by pandasql. Here is my function:

def getPolypsOfPaitentBasedOnSize(self,size):


   smallPolypQuery = """ 
                       select *
                       from     polyp 
                       where polyp.`Size of Sessile in Words` ==  """ +size

   smallPolyps = ps.sqldf(smallPolypQuery)

When i run the code, i get the below error:

    raise PandaSQLException(ex)
pandasql.sqldf.PandaSQLException: (sqlite3.OperationalError) no such column: Small
[SQL:  
                       select *
                       from     polyp 
                               where polyp.`Size of Sessile in Words` ==  Small]

it seems that, i have to somehow make it like

 where polyp.`Size of Sessile in Words` == 'Small'

but, i don't know, how to do it!

Update:

I have tired the below solution and also there is no error but the query does not return anything

""" 
    select *
    from     polyp 
    where polyp.`Size of Sessile in Words` ==  " """ +size+ """ " """

I am sure (if the size="Small")the statement like below will work for me:

where polyp.`Size of Sessile in Words` ==  "Small"

Solution

  • format can be used.

    size = 'Small'
    
    smallPolypQuery = """ 
    select *
    from   polyp 
    where  polyp.`Size of Sessile in Words` ==  {0}""".format(size)
    
    print(smallPolypQuery)
    

    The resule is:

    select *
    from   polyp 
    where  polyp.`Size of Sessile in Words` ==  Small
    

    If you need quote then put it to the smallPolypQuery such as:

    smallPolypQuery = """ 
    select *
    from   polyp 
    where  polyp.`Size of Sessile in Words` ==  "{0}" """.format(size)