I am trying to execute an SQL Query in python. I have a pandas dataframe which is necessary for passing CompanyId column to my query.
JavaScript
x
8
1
data["CompanyId"].head()
2
3
0 16559
4
1 16753
5
2 16757
6
3 17491
7
4 17532
8
I want to use the CompanyId inside the IN
operator of SQL. I tried,
JavaScript
1
4
1
x = ",".join(str(data["CompanyId"]))
2
3
myquery = "SELECT * FROM mydb WHERE CompanyId IN (" + x + ")"
4
But no chance. I can create the very same query thanks to the paste function in R
like,
JavaScript
1
2
1
paste0('SELECT * FROM mydb WHERE CompanyId IN (',paste(data[,"CompanyId"],collapse=","),')')
2
But I am unable to the this in python
.
At the end, I’d like to execute the query like below,
JavaScript
1
2
1
pd.read_sql_query(myquery,conn)
2
Btw, I am not sure if this is the best way to execute a query through python. I am open to any advise that makes my life easier.
Thank you in advance!
Advertisement
Answer
The problem seems to be that you’re converting your dataframe into a string, rather than mapping its elements to strings. This would change
",".join(str(data["CompanyId"]))
to
",".join(map(str,df["CompanyId"]))