如何在Python中通过cur.execute实现多日期循环批量查询
自动化循环执行月度查询并合并结果
步骤1:生成目标日期序列
先批量生成你需要的每月第一天日期,转换成01Jan2021格式的字符串:
import pandas as pd import locale # 确保月份缩写为英文(中文系统需设置) locale.setlocale(locale.LC_TIME, 'en_US.UTF-8') # 生成2021年1月到2022年10月的每月第一天 start_date = '2021-01-01' end_date = '2022-10-01' dates = pd.date_range(start=start_date, end=end_date, freq='MS') # MS = 每月第一天 # 转换成目标格式字符串 date_list = [date.strftime('%d%b%Y') for date in dates]
步骤2:修改查询函数,支持传入日期参数
原函数依赖全局变量,改成传入参数更规范,同时避免变量名和数据库字段名冲突(把原Date变量改成target_date):
import pandas as pd def run_query(target_date): # 修正查询语句:用占位符避免字段名冲突 query = """select distinct A.ID, count(A.Name) as Name_Count from A, B where %(target_date)s between A.Start and A.End and B.Status='Y' group by A.ID""" try: cur = conn() # 假设conn()是你已定义的数据库连接函数 cur.execute(query, {'target_date': target_date}) df = pd.DataFrame(cur.fetchall()) df.columns = [x[0] for x in cur.description] # 添加日期列,方便后续区分数据来源 df['Query_Date'] = target_date print(f'{target_date} 查询完成') return df except Exception as e: print(f'{target_date} 查询失败:{str(e)}') return pd.DataFrame() finally: if cur: cur.close() # 关闭游标释放资源
步骤3:循环执行查询并合并结果
遍历所有日期,收集查询结果后合并成一个DataFrame:
# 存储所有查询结果的列表 all_data = [] for date in date_list: result_df = run_query(date) if not result_df.empty: all_data.append(result_df) # 合并所有结果 combined_df = pd.concat(all_data, ignore_index=True) # 查看合并后的数据 print(combined_df.head()) # 保存到CSV方便后续分析 combined_df.to_csv('monthly_trend_data.csv', index=False)
优化建议:复用数据库连接
如果每次调用conn()都会新建连接,循环多次会造成资源浪费,建议提前创建一次连接:
# 提前建立连接 db_conn = conn() try: all_data = [] for date in date_list: result_df = run_query_with_conn(db_conn, date) if not result_df.empty: all_data.append(result_df) finally: db_conn.close() # 最后关闭连接 # 对应的函数修改为接受连接参数 def run_query_with_conn(db_conn, target_date): query = """select distinct A.ID, count(A.Name) as Name_Count from A, B where %(target_date)s between A.Start and A.End and B.Status='Y' group by A.ID""" try: cur = db_conn.cursor() cur.execute(query, {'target_date': target_date}) df = pd.DataFrame(cur.fetchall()) df.columns = [x[0] for x in cur.description] df['Query_Date'] = target_date print(f'{target_date} 查询完成') return df except Exception as e: print(f'{target_date} 查询失败:{str(e)}') return pd.DataFrame() finally: if cur: cur.close()
内容的提问来源于stack exchange,提问作者Ruyi
相关产品推荐
相关产品推荐

