键“PRIMARY”的重复条目“0”,我无法使用自动增量,因为值并不总是增加

2024-06-24 13:39:13 发布

您现在位置:Python中文网/ 问答频道 /正文


**我想做什么**

我一直试图通过tkinter向表中插入一条记录,我想在mysql上看到插入的记录。

问题
在向tkinter输入记录后,我收到以下错误。我研究了在线发布的相同错误的解决方案,但对列代码(带有主键的代码)使用自动增量。但是,我不能使用auto_increment,因为列代码的值并不总是增加。我也尝试过删除列的主键,但仍然出现相同的错误。对此有何见解?


**错误:**
*mysql.connector.errors.IntegrityError:1062(23000):键“PRIMARY”的重复条目“0”*
**创建表的代码:*
#table
cursor=mycon.cursor(buffered=True)
cursor.execute("use iv")
cursor.execute("drop table if exists salesperson")
create_table='''create table salesperson
(
code int(4) primary key,
name varchar(15),
salary int,
itcode char
)'''
cursor.execute(create_table)

**从tkinter/python向mysql插入数据的代码:**
from tkinter import *
from tkinter.messagebox import showinfo

def add_data():
    code=tcode.get('1.0',END) #retrieve input
    name=tname.get('1.0',END)
    salary=tsal.get('1.0',END)
    itcode=titcode.get('1.0',END)

    #DATABASE CONNECTION
    if code=="" or name=="" or salary=="" or itcode=="":
        messagbox.showinfo("Please fill all the fields")
    else:
        import mysql.connector as sqltor
        connection=sqltor.connect(host="localhost",user="root",password="  ",database="iv")
        tkcursor=connection.cursor()
        tkcursor.execute("Insert into salesperson values (code,'name',salary,'itcode')")
        connection.commit()
        messagebox.showinfo("Records inserted")
        tkcursor.close()

Tags: 代码nameexecutegettkinter错误记录mysql
1条回答
网友
1楼 · 发布于 2024-06-24 13:39:13

问题出在INSERT语句中:

tkcursor.execute("Insert into salesperson values (code,'name',salary,'itcode')")

当您在这样的SQL语句中引用标识符时,它是SQL标识符,而不是Python变量。在这种情况下这不是一个错误,因为您的表恰好有名为codesalary的列

但这些列的价值是什么?由于这是一条INSERT语句,根据定义,在计算VALUES()子句时,该行还不存在。因此,该行所有列的值都为NULL。就好像你做了这件事:

tkcursor.execute("Insert into salesperson values (NULL,'name',NULL,'itcode')")

因为code是主键,所以它不能为NULL。即使该列没有定义默认值,MySQL也有一个“默认值”的概念。也就是说,在没有明确定义的默认值的情况下,如果不接受NULL,则每个数据类型都将转换为适当的隐式默认值(有关这方面的文档,请参见https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html)。对于整数,隐式默认值为0。所以你的陈述就像你做的那样:

tkcursor.execute("Insert into salesperson values (0,'name',NULL,'itcode')")

如何解决这个问题?您应该使用参数来帮助您将Python变量的值获取到SQL INSERT语句中。这样,将使用Python变量code,而不是同样名为code的SQL列。nbk的上述评论暗示了这一点

tkcursor=connection.cursor(prepared=True)
tkcursor.execute("Insert into salesperson values (%s,'name',%s,'itcode')", (code, salary,)
connection.commit()

有关更多信息,请参见https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorprepared.html

相关问题 更多 >