尝试使用以下代码插入数据库表时出现错误
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, '')
如果只有三个参数并且我传递了所有三个参数,我不知道为什么会收到错误。
传递到 val 的子数组之一在原始文本文件中格式不正确,这意味着子数组有 4 个值,而不是预期的 3 个。我修复了文本文件,一切都从那里开始工作。