简体   繁体   中英

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

I have a list with three elements in it and I want to iterate over the list to execute query one after another element in the list. For example,

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

I want to execute query "SELECT name, zipcode, state FROM survey WHERE zipcode IN 1000" first, and then "SELECT name, zipcode, state FROM survey WHERE zipcode IN 10018" and last query "SELECT name, zipcode, state FROM survey WHERE zipcode IN 11201"

I also want to put the retrieved data in 3 separate dataframes. Here's how I executed the query,

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)

Consider pandas.read_sql to directly query a database without need of a cursor. Also, try saving three dataframes in a list or dictionary.

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

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