MariaDB报not enough arguments for format string错误,求原因及修复方法
错误原因
你写的SQL里用了%Y-%m-%d %H:%i:%s作为日期格式化字符串,其中的%s会被MySQLdb(SQLAlchemy底层驱动)误认为是参数占位符,但你并没有给这个占位符传对应参数,因此触发了"not enough arguments for format string"错误。
哪怕用了f-string拼接SQL,驱动也会优先解析SQL里的%占位符,和你拼接的内容无关。
修复方案
有两种简单的解决办法:
方法1:转义SQL里的百分号
把格式字符串里的%s改成%%s,f-string会自动把%%转成单个%传到MySQL,驱动就不会把它当成参数占位符了:
for i, row in tables.iterrows(): year = row['Tables_in_log_20220114_msn'][4:8] month = row['Tables_in_log_20220114_msn'][8:10] date = row['Tables_in_log_20220114_msn'][10:12] result = year + '-' + month + '-' + date res = pd.read_sql( f'''SELECT id, user_id, ipaddress, status, error, STR_TO_DATE(CONCAT('{result}', ' ', time), '%Y-%m-%d %H:%i:%%s') as 'datetime' FROM {row['Tables_in_log_20220114_msn']} LIMIT 5;''', con=engine) break
方法2:单独定义日期格式字符串
把日期格式字符串抽出来单独定义,避免和驱动的参数占位符逻辑冲突:
for i, row in tables.iterrows(): year = row['Tables_in_log_20220114_msn'][4:8] month = row['Tables_in_log_20220114_msn'][8:10] date = row['Tables_in_log_20220114_msn'][10:12] result = year + '-' + month + '-' + date date_format = "%Y-%m-%d %H:%i:%s" res = pd.read_sql( f'''SELECT id, user_id, ipaddress, status, error, STR_TO_DATE(CONCAT('{result}', ' ', time), '{date_format}') as 'datetime' FROM {row['Tables_in_log_20220114_msn']} LIMIT 5;''', con=engine) break
额外提醒:动态拼接表名时要注意SQL注入风险,如果tables里的表名来自不可信来源,一定要做合法性校验。
内容的提问来源于stack exchange,提问作者Qukz
相关产品推荐
相关产品推荐

