Import data from python (probleme with where condition)

I work in Python I have code that allows me to import a dataset that works fine. However in my dataset I have 3 different patients and I would like to import only the patient that interests me (possible by adding the WHERE statement in the SQL query. So the following code works:

def importecdata():
query2 = "SELECT TECDATA.[Vol_Recalage_US_VD], TECDATA.[Vol_Recalage_Us_VG], TECDATA.[SUBJID] FROM TECDATA  INNER JOIN MEDDATA ON TECDATA.DateTime = MEDDATA.DateTime WHERE TECDATA.[SUBJID]='patient14';"
dftec1 = pd.read_sql(query2, sql_conn, chunksize=100000)
dftec = pd.concat(dftec1)
return(dftec)

It return the patient 14 data But now I want to put the patient’s name as a variable in my function so I made the following code:

def importecdata(patient):
query2 = "SELECT TECDATA.[Vol_Recalage_US_VD], TECDATA.[Vol_Recalage_Us_VG], TECDATA.[SUBJID] FROM TECDATA  INNER JOIN MEDDATA ON TECDATA.DateTime = MEDDATA.DateTime WHERE TECDATA.[SUBJID]=patient;"
dftec1 = pd.read_sql(query2, sql_conn, chunksize=100000)
dftec = pd.concat(dftec1)
return(dftec)

I chek and the patient variable got the value patient14. But it don’t work… i try to modify the value of the variable patient to ‘patient14’ it don’t work too i have the same error : invalid column name xa0: ‘patient’. So the code works, the problem is from the “where” condition with the patient variable

(sorry for my english i’m french)

Answer

You have to add your patient value in the query string check below code:

def importecdata(patient):
    query2 = "SELECT TECDATA.[Vol_Recalage_US_VD], TECDATA.[Vol_Recalage_Us_VG], TECDATA.[SUBJID] FROM TECDATA  INNER JOIN MEDDATA ON TECDATA.DateTime = MEDDATA.DateTime WHERE TECDATA.[SUBJID]='{0}';"
    query2 = query2.format(patient)
    dftec1 = pd.read_sql(query2, sql_conn, chunksize=100000)
    dftec = pd.concat(dftec1)
    return(dftec)