0

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.

data["CompanyId"].head()

0    16559
1    16753
2    16757
3    17491
4    17532

I want to use the CompanyId inside the IN operator of SQL. I tried,

x = ",".join(str(data["CompanyId"]))

myquery =  "SELECT * FROM mydb WHERE CompanyId IN (" +  x  + ")"

But no chance. I can create the very same query thanks to the paste function in R like,

paste0('SELECT * FROM mydb WHERE CompanyId IN (',paste(data[,"CompanyId"],collapse=","),')')

But I am unable to the this in python.

At the end, I'd like to execute the query like below,

pd.read_sql_query(myquery,conn)

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!

2
  • What do you mean by 'no chance'? Are you getting errors? Unexpected results? Commented Sep 26, 2021 at 16:45
  • I meant, It gives inappropriate string output. Commented Sep 26, 2021 at 16:48

3 Answers 3

1

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"]))

Sign up to request clarification or add additional context in comments.

Comments

1

See below

import pandas as pd
data = [{'companyId':12},{'companyId':19},{'companyId':121}]
df = pd.DataFrame(data)
ids = [str(x) for x in df['companyId'].tolist()]
myquery =  f"SELECT * FROM mydb WHERE CompanyId IN ({','.join(ids)})"
print(myquery)

output

SELECT * FROM mydb WHERE CompanyId IN (12,19,121)

1 Comment

This also gives the right output. I cannot upvote because of my reputation. Sorry.
1

You can convert the ids to strings using astype.

ids = ','.join(data['CompanyId'].astype(str).to_list())

myquery =  f"SELECT * FROM mydb WHERE CompanyId IN ({ids})"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.