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

时间:2017-04-18 15:31:53

标签: python sql database

我有一个包含三个元素的列表,我希望迭代列表以在列表中逐个执行查询。例如,

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个独立的数据帧中。这是我执行查询的方式,

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)

1 个答案:

答案 0 :(得分:0)

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

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()