首页 > 解决方案 > 从用户那里获取数据并将其保存在数据库中

问题描述

我正在尝试从用户那里获取数据并将其插入到我的数据库中。一切正常,直到我点击“保存”按钮。然后我得到那些错误:

Tkinter 回调 Traceback 中的异常(最近一次调用最后一次):文件“/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/init .py ”,第 1705 行,调用中 return self.func(*args) File "/Users/alidemirkazik/PycharmProjects/GUI_Test/GUI_Test.py", line 51, in add_customer mycursor.execute(sql, val) File "/Users/alidemirkazik/PycharmProjects/GUI_Test/venv/ lib/python3.7/site-packages/mysql/connector/cursor.py”,第 551 行,在执行 self._handle_result(self._connection.cmd_query(stmt)) 文件“/Users/alidemirkazik/PycharmProjects/GUI_Test/venv/ lib/python3.7/site-packages/mysql/connector/connection.py”,第 490 行,在 cmd_query 结果 = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) 文件“/Users/alidemirkazik/PycharmProjects/ GUI_Test/venv/lib/python3.7/site-packages/mysql/connector/connection.py",第 395 行,在 _handle_result 中引发 errors.get_exception(packet) mysql.connector.errors.DatabaseError: 1366 (HY000):不正确的整数值:第 1 行的列 'ID' 的 ''

感谢是否有人可以帮助我。谢谢!

r = Tk()
r.title('Adding New Customer')
r.geometry("175x62")


def quit():
    r.destroy()


def contact():
    contact_window = Toplevel(r)
    Label(contact_window, text='ID').grid(row=0)
    Label(contact_window, text='Name').grid(row=1)
    Label(contact_window, text='Address').grid(row=2)
    Label(contact_window, text='Country').grid(row=3)
    Label(contact_window, text='Age').grid(row=4)
    input1 = Entry(contact_window)
    input2 = Entry(contact_window)
    input3 = Entry(contact_window)
    input4 = Entry(contact_window)
    input5 = Entry(contact_window)
    input1.grid(row=0, column=1)
    input2.grid(row=1, column=1)
    input3.grid(row=2, column=1)
    input4.grid(row=3, column=1)
    input5.grid(row=4, column=1)

    first_id = input1.get()
    first_name = input2.get()
    first_address = input3.get()
    first_country = input4.get()
    first_age = input5.get()

    def add_customer():
        mycursor = mydb.cursor()
        sql = "INSERT INTO customers (ID, Name, Address, Country, Age) VALUES (%s, %s, %s, %s, %s)"
        val = (first_id, first_name, first_address, first_country, first_age)
        mycursor.execute(sql, val)
        mydb.commit()

    button3 = Button(contact_window, text="Save", command=add_customer)
    button3.grid(row=5, column=1)


button1 = Button(r, text="Contact", command=contact).pack(fill=X, ipady=5)
button2 = Button(r, text="Exit", command=quit).pack(fill=X, ipady=5)

r.mainloop()

标签: pythonmysqltkinter

解决方案


看起来您要添加的 ID 不是整数,这是数据库预期的类型。

我认为您只需要将 first_id 转换为整数。所以,这样的事情:

val = (int(first_id), first_name, first_address, first_country, first_age)

此外,我认为允许最终用户输入数据库的 ID 并不是一个好主意。我建议您让数据库以增量方式自动填充新条目的 ID。


推荐阅读