我一直试图通过tkinter向表中插入一条记录,我想在mysql上看到插入的记录。
问题
在向tkinter输入记录后,我收到以下错误。我研究了在线发布的相同错误的解决方案,但对列代码(带有主键的代码)使用自动增量。但是,我不能使用auto_increment,因为列代码的值并不总是增加。我也尝试过删除列的主键,但仍然出现相同的错误。对此有何见解?
#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)
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()
问题出在INSERT语句中:
当您在这样的SQL语句中引用标识符时,它是SQL标识符,而不是Python变量。在这种情况下这不是一个错误,因为您的表恰好有名为
code
和salary
的列但这些列的价值是什么?由于这是一条INSERT语句,根据定义,在计算VALUES()子句时,该行还不存在。因此,该行所有列的值都为NULL。就好像你做了这件事:
因为
code
是主键,所以它不能为NULL。即使该列没有定义默认值,MySQL也有一个“默认值”的概念。也就是说,在没有明确定义的默认值的情况下,如果不接受NULL,则每个数据类型都将转换为适当的隐式默认值(有关这方面的文档,请参见https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html)。对于整数,隐式默认值为0。所以你的陈述就像你做的那样:如何解决这个问题?您应该使用参数来帮助您将Python变量的值获取到SQL INSERT语句中。这样,将使用Python变量
code
,而不是同样名为code
的SQL列。nbk的上述评论暗示了这一点有关更多信息,请参见https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorprepared.html
相关问题 更多 >
编程相关推荐