Python动态生成SQL带引号的月份变量问题
解决方案
一、修复字符串生成格式
你的问题出在repr(e)对整数的处理上,它不会给整数添加单引号。可以直接在生成每个月份字符串时手动添加单引号,同时简化原来的循环代码:
from datetime import datetime current_month = datetime.now().month last_month = current_month - 1 # 直接生成1到last_month的月份列表,替代循环 month_list = list(range(1, last_month + 1)) # 为每个月份添加单引号后拼接 months = ", ".join(f"'{month}'" for month in month_list)
执行后months会生成符合要求的格式,比如当前月份是4时,结果为'1', '2', '3',可以直接嵌入SQL的IN子句中。
二、更安全的替代方案:参数化查询
直接拼接字符串到SQL语句存在SQL注入风险,建议使用数据库驱动支持的参数化查询方式,它会自动处理参数的格式转义,既安全又省心。
以Python连接MySQL(pymysql库)为例:
from datetime import datetime import pymysql current_month = datetime.now().month last_month = current_month - 1 month_list = list(range(1, last_month + 1)) current_year = datetime.now().year # 建立数据库连接(替换为你的实际配置) conn = pymysql.connect(host="your_host", user="your_username", password="your_password", database="your_db") cursor = conn.cursor() # 生成与月份数量匹配的占位符,用%s作为参数占位符 placeholders = ", ".join(["%s"] * len(month_list)) # 构造带占位符的SQL语句 sql = f""" SELECT * FROM database WHERE year = %s AND month IN ({placeholders}) """ # 执行查询,把年份和月份列表作为参数传入 cursor.execute(sql, (current_year, *month_list)) results = cursor.fetchall() # 关闭资源 cursor.close() conn.close()
如果使用其他数据库(如PostgreSQL、SQLite),只需要调整占位符格式(比如PostgreSQL用%s,SQLite用?),核心逻辑一致。
内容的提问来源于stack exchange,提问作者LennartPfeiler
相关产品推荐
相关产品推荐

