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

Tkinter插入数据至含自增ID与timestamp的MySQL时报列数不匹配错误如何解决?

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

错误原因

你的employees表包含5个字段(id、name、surname、mobile、datetime),但你编写的INSERT语句没有指定要插入的列,MySQL会默认尝试将你传入的3个值依次匹配表中所有5个字段,因字段数量与值的数量不匹配,所以抛出该错误。

解决方法

推荐采用明确指定插入列的方式,既清晰又避免不必要的参数传递:

修改Python代码中的SQL执行语句,同时修正变量名不一致的问题(原代码中判断空值用entryName.get(),插入时却用name.get(),需统一):

def saveData():
    if entryName.get() == "" or surname.get() == "":
        messagebox.showerror("Error", "fields are empty")
    else:
        con = mysql.connector.connect(host="localhost", username="admin", password="12345", database="english")
        my_cursor = con.cursor()
        # 明确指定要插入的列,利用自增和默认值特性
        my_cursor.execute("INSERT INTO employees (name, surname, mobile) VALUES (%s, %s, %s)", 
                          (entryName.get(), surname.get(), mobile.get()))
        con.commit()
        con.close()
        viewdata()
        messagebox.showinfo('Success', 'Record has been inserted')

如果你想保留不指定列的写法,也可以给自增的id传NULL(MySQL会自动生成自增值),给datetime传DEFAULT让数据库使用默认值:

my_cursor.execute("INSERT INTO employees VALUES (NULL, %s, %s, %s, DEFAULT)", 
                  (entryName.get(), surname.get(), mobile.get()))

额外提醒

原代码中存在变量名不一致的问题:判断空值时用的是entryName.get(),但插入数据时写的是name.get(),这会导致变量未定义或取值错误,务必保持变量名统一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:32:14