当SQL查询中的列表作为参数时,如何在Python中执行查询

How to execute query in Python when list in SQL query as parameter

我有一个包含三个元素的列表,我想遍历该列表以逐个执行列表中的另一个元素的查询。例如,

1
2
zipcode_list = ['10000', '10018', '11201']
sql ="SELECT name, zipcode, state FROM survey WHERE zipcode IN (%s)"

我想先执行查询"SELECT name, zipcode, state FROM survey WHERE zipcode IN 1000",然后执行"SELECT name, zipcode, state FROM survey WHERE zipcode IN 10018"和最后一个查询"SELECT name, zipcode, state FROM survey WHERE zipcode IN 11201"

我还想将检索到的数据放在3个独立的数据帧中。以下是我执行查询的方式,

1
2
3
4
5
6
7
zipcode_list = ['10000', '10018', '11201']
sql ="SELECT name, zipcode, state FROM survey WHERE zipcode IN (%s)"    
in_p = ', '.join(list(map(lambda x: '%s', zipcode_list)))
sql = sql % in_p
df = cursor.execute(sql, zipcode_list).fetchall()
for dfs in df:
    df = pd.DataFrame(df)


考虑pandas.read_sql直接查询数据库而不需要光标。另外,尝试在列表或字典中保存三个数据帧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import pandas as pd

conn = ...              # DB CONNECTION OBJECT

zipcode_list = ['10000', '10018', '11201']  
sql ="SELECT name, zipcode, state FROM survey WHERE zipcode = %s"  

dfList = []
for z in zipcode_list:
   dfList.append(pd.read_sql(sql, conn, params=[z]))

dfDict = {}
for z in zipcode_list:
   dfDict[z] = pd.read_sql(sql, conn, params=[z])

conn.close()