Python嵌套for循环引发rps_table_q_2查询重复输出的解决方法
SQL Server循环查询重复输出的修复方案
重复输出SQL的核心原因:你把SQL生成、打印或执行的逻辑错误放到了内层结果遍历的循环中,而非外层的金额遍历循环。
假设amount_ack_missing_l长度为3,每个金额对应的SQL查询返回2条结果,内层循环会把同一条SQL重复打印2次,最终3个金额就会输出6条重复SQL,和你遇到的错误完全匹配。
逻辑调整原则
- 外层循环负责遍历待查询金额,每个金额对应一次SQL生成、执行操作,SQL打印仅需放在外层一次,确保每个金额对应一条SQL输出。
- 内层循环仅负责处理查询返回的结果集,做金额格式化、缺失文件信息拼接这类数据处理操作,不放置SQL相关逻辑。
保留嵌套循环的修复代码
from datetime import datetime, timedelta # 初始化常量与全局列表 cd = (datetime.now() - timedelta(days=1)).strftime('%m/%d/%Y') missing_file_l = [] rps_amount_l2 = [] # 补全遗漏的列表初始化 # 外层循环:遍历金额,每个金额对应一次SQL执行 for amount in amount_ack_missing_l: print("AMOUNT", amount) # SQL生成、执行、打印全部放在外层,每个金额仅执行一次 rps_table_q_2 = f"""select * from rps..sendfile where processingdate = '{cd}' and datasetname like '%ICL%' and paymenttotamt = '{amount}' """ print("生成的查询SQL:", rps_table_q_2) # 禁止把这行放到内层循环 rps_table_results = sql_server_cursor.execute(rps_table_q_2).fetchall() # 内层循环:仅处理结果集 for rps in rps_table_results: rps_amount_f = str(rps[18]).rstrip('0') rps_amount_f = ("{:,}".format(float(rps_amount_f))) rps_amount_l2.append(rps_amount_f) missing_file = f"Missing filename {rps[6]} in the amount of ${rps_amount_f}" missing_file_l.append(missing_file)
整合为无嵌套单循环的版本
如果不想保留嵌套循环,可以先批量执行所有金额的查询,再统一处理所有返回结果,拆分两个独立单循环完成操作:
from datetime import datetime, timedelta cd = (datetime.now() - timedelta(days=1)).strftime('%m/%d/%Y') missing_file_l = [] rps_amount_l2 = [] all_query_results = [] # 第一个单循环:批量执行所有金额的SQL,仅做查询 for amount in amount_ack_missing_l: rps_table_q_2 = f"""select * from rps..sendfile where processingdate = '{cd}' and datasetname like '%ICL%' and paymenttotamt = '{amount}' """ print("生成的查询SQL:", rps_table_q_2) all_query_results.extend(sql_server_cursor.execute(rps_table_q_2).fetchall()) # 第二个单循环:统一处理所有查询返回的结果 for rps in all_query_results: rps_amount_f = str(rps[18]).rstrip('0') rps_amount_f = ("{:,}".format(float(rps_amount_f))) rps_amount_l2.append(rps_amount_f) missing_file = f"Missing filename {rps[6]} in the amount of ${rps_amount_f}" missing_file_l.append(missing_file)
额外优化建议
生产环境不要用f-string拼接SQL,存在SQL注入风险,建议改为参数化查询:
# 参数化SQL写法 rps_table_q_2 = """select * from rps..sendfile where processingdate = ? and datasetname like '%ICL%' and paymenttotamt = ? """ # 执行时传入参数,不要直接拼接 rps_table_results = sql_server_cursor.execute(rps_table_q_2, (cd, amount)).fetchall()
内容的提问来源于stack exchange,提问作者iampython34
相关产品推荐
相关产品推荐

