简体   繁体   English

如何在 SQL Where IN 子句中使用 Python 列表?

[英]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.我有一个 CSV 文件,其中包含几列和 800 条记录,其中一列是我需要在 SQL 查询中过滤的变量。

_ _

I thought about reading that CSV as a Dataframe, ->我想过把 CSV 读成 Dataframe,->

then get a list from that DF, ->然后从那个 DF 中获取一个列表,->

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

_ _

How can I do it with Python?如何使用 Python 做到这一点?

Thanks谢谢

Thanks @wilian, but I meant how could I do this using python because I didnt know, besides which library to use谢谢@wilian,但我的意思是我怎么能用 python 做到这一点,因为我不知道,除了使用哪个库

I figure it out a way to do it:我想办法做到这一点:

Imported my csv file into a dataframe将我的 csv 文件导入 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需要这样做,因为 SQL Where X IN ('') 子句需要用 ' 和逗号编写

Then I got a single string like this然后我得到一个这样的字符串

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

Then I used read_sql from pandas using a f'string然后我使用 f'string 从 pandas 使用 read_sql

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

result = pd.read_sql(query,conn)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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