Home > OS >  How to use variables in SQL statement in Python using IN statement
How to use variables in SQL statement in Python using IN statement

Time:03-25

I have dataframe with 2 cols, id and email. Now I want to write sql query to use in python which dynamically fetches only those emails which are present in df['email']. The sql equivalent of this query will be something like this

select id, email from xdb where email in (email1, email2, ...);

But I want something like df['email'] instead of (email1, email2, ...). How can I put a variable in place of writing all those email one by one? And am using pandas pd.read_sql function to run the queries and mysql.

CodePudding user response:

use:

pd.read_sql(f"select id, email from xdb where email in {tuple(df.email.values)}", conn)
  • Related