问题描述
我是python的初学者。当我将记录插入数据库时。记录未添加。我在数据库id
,name
中有两列。在MysqL自动增量中设置的ID。
from tkinter import *
import MysqL.connector # Importing Connector package
def Ok():
result = e1.get()
MysqLdb=MysqL.connector.connect(host="localhost",user="root",password="",database="empdb")#established connection between your database
mycursor=MysqLdb.cursor()
try:
mycursor.execute("insert into records values(%s)",(result,))
MysqLdb.commit()
print('Record inserted successfully...')
except Exception as e:
print(e)
MysqLdb.rollback()
MysqLdb.close()
raise Exception("Sorry,no numbers below zero")
root = Tk()
root.title("Employee Salary Calculation System")
root.geometry("300x400")
global e1
Label(root,text="Employee Name").place(x=10,y=10)
e1 = Entry(root)
e1.place(x=100,y=10)
Button(root,text="Cal",command=Ok,height = 1,width = 3).place(x=10,y=150)
root.mainloop()
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\kobinath\AppData\Local\Programs\Python\python38-32\lib\tkinter\__init__.py",line 1883,in __call__
return self.func(*args)
File "C:/Users/kobinath/PycharmProjects/pythonProject4/employee.py",line 20,in Ok
raise Exception("Sorry,no numbers below zero")
Exception: Sorry,no numbers below zero
我遇到了上面的错误。
解决方法
如果您尝试在python中捕获异常,则可以使用以下代码:
tf.gatherr_nd
这将帮助您找出正在发生的错误类型。
看起来您在尝试将数据插入表时遇到问题。
让我们假设我有一个名为try:
x = int(input('Enter a number'))
except Exception as e:
print (e)
的表,它有两列customers
和name
,那么我可以编写以下语句将记录插入表中。 / p>
address
然后进行提交以提交记录。如果您有一栏以上,那么在INSERT语句中提供这些详细信息就很重要。
,在您的代码中,此行
raise Exception("Sorry,no numbers below zero")
仍然执行。请检查您要做什么并修复它。
但是您不能插入记录的原因是:
mycursor.execute("insert into records values(result)")
请注意,引号内的整个字符串都作为SQL语句执行。您确定“结果”在您的上下文中有效吗?这可能使MySQL引发了错误。我相信您的意思是这样:
mycursor.execute("insert into records values(%s)",(result,))