我的代码有些问题。所以,我想通过在表单中写入数据来向Accces添加数据。 (我在编程方面不太好。)
from tkinter import *
import pypyodbc
import ctypes
form=Tk ()
form.title ("Add data")
form.geometry ('400x200')
#Create connection
con = pypyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL={MS Access};DriverId=25;DefaultDir=C:/Users/HP/Desktop/PITL;DBQ=C:/Users/HP/Desktop/PITL/PITL.mdb;')
cursor = con.cursor ()
a = Entry (form, width=20, font="Arial 16")
a.pack ()
b = Entry (form, width=20, font="Arial 16")
b.pack ()
def Add (event):
cursor.execute ("INSERT INTO Crime (`Number_of_article`, `ID_of_criminal`) VALUES (?, ?)", (a, b))
con.commit ()
cursor.close ()
con.close ()
Button=Button(form, text = 'PUSH ME')
Button.pack ()
Button.bind ('<Button-1>', Add)
form.mainloop ()
我的错误是:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\HP\Desktop\PITL\ADD DATA.py", line 19, in Add
cursor.execute ("INSERT INTO Crime (`Number_of_article`, `ID_of_criminal`) VALUES (?, ?)", (a, b))
File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypyodbc-1.3.4-py3.6.egg\pypyodbc.py", line 1470, in execute
self._free_stmt(SQL_CLOSE)
File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypyodbc-1.3.4-py3.6.egg\pypyodbc.py", line 1987, in _free_stmt
raise ProgrammingError('HY000','Attempt to use a closed connection.')
pypyodbc.ProgrammingError: ('HY000', 'Attempt to use a closed connection.')
此外,如果我将此代码(下面)更改为a = '*any number*' b = '*any number*'
,程序将正常工作
a = Entry (form, width=20, font="Arial 16")
a.pack ()
b = Entry (form, width=20, font="Arial 16")
b.pack ()
答案 0 :(得分:2)
在调用Add之前关闭连接,将关闭调用移到代码底部。
答案 1 :(得分:0)
.close()语句的一般最佳实践是将它们放在代码的末尾。但是在这种情况下,这可能会产生错误。暂时尝试删除.close()语句。
from tkinter import *
import pypyodbc
import ctypes
form=Tk ()
form.title ("Add data")
form.geometry ('400x200')
#Create connection
con = pypyodbc.connect('DRIVER={Microsoft Access Driver(*.mdb)};UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5; MaxScanRows=8;MaxBufferSize=2048;FIL={MS Access};DriverId=25;DefaultDir=C:/Users/HP/Desktop/PITL;DBQ=C:/Users/HP/Desktop/PITL/PITL.mdb;')
cursor = con.cursor ()
a = Entry (form, width=20, font="Arial 16")
a.pack ()
b = Entry (form, width=20, font="Arial 16")
b.pack ()
def Add (event):
cursor.execute ("INSERT INTO Crime (`Number_of_article`, `ID_of_criminal`) VALUES (?, ?)", (a, b))
Button=Button(form, text = 'PUSH ME')
Button.pack ()
Button.bind ('<Button-1>', Add)
form.mainloop ()
con.commit ()