将其分为三个部分,以帮助隔离问题并提高可读性:
- 构建SQL字符串
- 设定参数值
- 执行pandas.read_sql_query
建立SQL
首先,请确保
?正确设置占位符。结合使用str.format和str.join和len可以
?根据
member_list长度动态填充s
。以下示例假定3个
member_list元素。例
退货member_list = (1,2,3)sql = """select member_id, yearmonth from queried_table where yearmonth between {0} and {0} and member_id in ({1})"""sql = sql.format('?', ','.join('?' * len(member_list)))print(sql)
select member_id, yearmonthfrom queried_tablewhere yearmonth between ? and ?and member_id in (?,?,?)
设置参数值
现在确保将参数值组织成一个 平面 元组
例退货# generator to flatten values of irregular nested sequences,# modified from answers http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-pythondef flatten(l): for el in l: try: yield from flatten(el) except TypeError: yield elparams = tuple(flatten((201601, 201603, member_list)))print(params)
(201601, 201603, 1, 2, 3)
执行
最后在通话中将
sql和
params值组合在一起
read_sql_query
query = pd.read_sql_query(sql, db2conn, params)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)