简体   繁体   中英

How can I use a Python List in a SQL Where IN Clause?

I have a CSV file with a few columns and 800 records, and one of those columns is a variable that I need to filter in a SQL Query.

_

I thought about reading that CSV as a Dataframe, ->

then get a list from that DF, ->

and then use the list in the WHERE X IN (List[0]','List[1]','[List[2']....)

_

How can I do it with Python?

Thanks

Thanks @wilian, but I meant how could I do this using python because I didnt know, besides which library to use

I figure it out a way to do it:

Imported my csv file into a dataframe

df = pd.read_csv(path)

Then I made a list of the column I needed

list = df['list'].tolist()

Then I turned that list into a single string

list1 = """' , '""".join([str(item) for item in list])
list2 = "'" + list1[:] + "'" + list1[0:0]

Needed to do that way because the SQL Where X IN ('') clause needs to be written with ' and commas

Then I got a single string like this

list2 = 'a','b','c'

Then I used read_sql from pandas using a f'string

query = f"SELECT * FROM table WHERE X IN ({list2})"

result = pd.read_sql(query,conn)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM