You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用executemany向MySQL插入文件数据时遇SQL参数未全用错误求助

问题描述

使用Python的mysql.connector库从文本文件向MySQL数据库的characters表插入数据时,收到错误提示:"Not all parameters were used in the SQL statement"。

代码片段

import mysql.connector
import re

mydb = mysql.connector.connect(
  host="",
  user="",
  password="",
  database ="db"
)
mycursor = mydb.cursor()

sql = "INSERT INTO characters (url, name, disambiguation) VALUES (%s, %s, %s)"
val = []
with open("text.txt","r",encoding="utf-8") as f:
    for line in f.readlines():
      x = re.findall(r'"(.*?)"', line)
      x= x[::-1]
      x.append("")
      val.append(x)

mycursor.executemany("INSERT INTO characters (name, url, disambiguation) VALUES (%s, %s, %s)", val)
mydb.commit()

处理后的val内容

[["'Lectron (Earth-12772)", '/wiki/%27Lectron_(Earth-12772)', ''], ["'Selka (Earth-928)", '/wiki/%27Selka_(Earth-928)', ''], ["'Spinner (Earth-616)", '/wiki/%27Spinner_(Earth-616)', ''],...]

表结构(执行DESCRIBE TABLE结果)

('name', 'varchar(255)', 'YES', '', None, '')
('url', 'varchar(255)', 'YES', '', None, '')
('disambiguation', 'varchar(255)', 'YES', '', None, '')

明明SQL语句有三个参数且已传入对应三个值,却仍报错,请问原因是什么?


原因分析与解决方法
  • 核心问题:部分行处理后生成的子列表长度不等于3
    代码通过re.findall(r'"(.*?)"', line)提取每行内容,反转后追加空字符串。如果某一行没有匹配到足够内容(比如re.findall返回空列表或仅1个元素),反转后的列表长度不足2,追加空字符串后总元素数仍不是3,和SQL语句里的3个%s参数不匹配,触发错误。

  • 验证方法
    在循环中添加打印语句,检查每行提取后的列表长度:

    for line in f.readlines():
        x = re.findall(r'"(.*?)"', line)
        print(f"当前行内容: {line}, 提取结果: {x}, 长度: {len(x)}")  # 新增此行
        x= x[::-1]
        x.append("")
        val.append(x)
    

    运行后会发现存在部分行的提取结果长度小于2,导致最终子列表长度不足3。

  • 修复方案
    确保每个子列表严格包含3个元素,可通过补全空字符串实现:

    for line in f.readlines():
        x = re.findall(r'"(.*?)"', line)[::-1]
        # 补全到2个元素,不足的用空字符串填充,再追加disambiguation的空值
        val.append([x[i] if i < len(x) else "" for i in range(2)] + [""])
    

内容的提问来源于stack exchange,提问作者roniinor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 21:12:33