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

Python执行MySQL插入语句报错:列数与值数不匹配

解决SQL插入时“Column count doesn't match value count at row 1”错误

你的错误原因很明确:INSERT语句中VALUES子句的列值总数和指定的列数不匹配。你指定了4列(Rollno, Name, Class, marks),但VALUES里直接写了8个值,数据库会默认把这8个值当成一行的字段去匹配4列,导致列数和值数不对应,触发报错。

要插入多行数据,需要把每组数据用单独的括号包裹、逗号分隔,正确的代码写法如下:

import mysql.connector

mydb = mysql.connector.connect(host="localhost", user="root", passwd="###", database="student", auth_plugin="mysql_native_password")
cursor = mydb.cursor()
# 修正VALUES子句,每行数据用括号分组
cursor.execute("insert into student(Rollno, Name, Class, marks) values(1,'carren','1B',100), (5,'john','2A',50)")
# 必须提交事务,否则数据不会写入数据库
mydb.commit()

更推荐用参数化查询的方式,还能避免SQL注入风险:

import mysql.connector

mydb = mysql.connector.connect(host="localhost", user="root", passwd="###", database="student", auth_plugin="mysql_native_password")
cursor = mydb.cursor()
# 定义要插入的多行数据
data = [
    (1, 'carren', '1B', 100),
    (5, 'john', '2A', 50)
]
# 使用%s作为占位符执行批量插入
cursor.executemany("insert into student(Rollno, Name, Class, marks) values(%s, %s, %s, %s)", data)
mydb.commit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 05:23:14