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

MySQL插入报错:Truncated incorrect double value,学生ID设为VARCHAR仍异常

问题解决:插入MySQL时出现"truncated incorrect double value"错误

核心原因

你的错误本质是插入值的顺序和student表的字段顺序不匹配,导致字符串类型的学生ID('1GA22AD061')被插入到了表中某个数值类型(比如INT/DOUBLE)的字段里——即便student_id本身是VARCHAR类型,这种错位也会触发类型转换错误。

解决步骤

  1. 确认表的字段结构
    先执行SQL查询明确student表的字段顺序和类型:

    DESC student;
    

    记录下所有字段的名称、顺序和类型,这是后续调整的基础。

  2. 修改INSERT语句,明确指定字段名
    永远不要依赖表的默认字段顺序,在INSERT语句中显式写出要插入的字段名,确保传入的值和字段一一对应。修改后的代码如下:

    def add_data(self):
        if self.var_dep.get() == "Select Department" or self.var_StudentID.get() == "" or self.var_Student_Name.get() == "":
            messagebox.showerror("Error", "All fields are required", parent=self.root)
        else:
            try:
                conn = mysql.connector.connect(host="localhost", user="root", password="Tejas@23", database="database_face_")
                my_cursor = conn.cursor()
                # 替换为你student表实际的字段名,确保顺序和值列表对应
                my_cursor.execute("""
                    INSERT INTO student (
                        dep, course, year, semester, student_id, student_name, gender, 
                        email, phone_no, dob, lecturer, address, class_div, mentor, radio1
                    ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
                """, (
                    self.var_dep.get(),
                    self.var_Course.get(),
                    self.var_Year.get(),
                    self.var_Semester.get(),
                    self.var_StudentID.get(),
                    self.var_Student_Name.get(),
                    self.var_Gender.get(),
                    self.var_email.get(),
                    self.var_Phone_no.get(),
                    self.var_DOB.get(),
                    self.var_Lecturer.get(),
                    self.var_Address.get(),
                    self.var_Class_div.get(),
                    self.var_Mentor.get(),
                    self.var_radio1.get()
                ))
                conn.commit()
                self.fetch_data()
                conn.close()
                messagebox.showinfo("Success", "Student details have been added successfully", parent=self.root)
            except mysql.connector.Error as err:
                messagebox.showerror("Error", f"Database Error: {err}", parent=self.root)
    

    注意:必须把代码中的字段名(dep、course等)替换成你表中实际的字段名称,保证和值列表的顺序完全匹配。

  3. 验证值与字段类型匹配
    额外检查每个变量的类型是否对应字段类型:

    • 比如phone_no如果是VARCHAR类型,确保self.var_Phone_no.get()返回字符串而非数字;
    • 日期字段dob要符合MySQL的日期格式(如YYYY-MM-DD)。

为什么之前的调整无效?

你之前修改student_id的类型却没解决问题,是因为错误根源不是student_id本身的类型,而是值被插入到了错误的字段位置。只有让每个值对应正确的字段,才能彻底解决类型不匹配的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:27:06