我尝试将信息添加到数据库(sqlite3,python 3.6) 我创建了tkinter小部件没有问题,但是在保存从输入小部件收集的信息并将其存储在数据库中时遇到了问题
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from tkinter import *
import sqlite3
master=Tk()
master.geometry('450x300')
master.title('add into database')
var_Name=StringVar()
var_Street=StringVar()
var_City=StringVar()
CreateDataBase = sqlite3.connect('MyDataBase.db')
QueryCurs = CreateDataBase.cursor()
#to create a table (Clients)
def CreateTable():
QueryCurs.execute('''CREATE TABLE IF NOT EXISTS Clients
(id INTEGER PRIMARY KEY, Name TEXT,Street TEXT,Town TEXT)''')
def AddEntry(Nom,Rue,Ville):
QueryCurs.execute('''INSERT INTO Clients (Name,Street,Town)
VALUES (?,?,?)''',(str(var_Name.get()),str(var_Street.get()),str(var_City.get())))
CreateTable()
label_Name=Label(master, text ='enter your name :')
label_Name.pack()
entry_Name=Entry(master,textvariable=var_Name)
entry_Name.pack()
label_Street=Label(master, text ='enter street :')
label_Street.pack()
entry_Street=Entry(master,textvariable=var_Street)
entry_Street.pack()
label_City=Label(master, text ='enter city :')
label_City.pack()
entry_City=Entry(master,textvariable=var_City)
entry_City.pack()
btn_Valider=Button(master,text='validate', command=AddEntry)
btn_Valider.pack()
CreateDataBase.commit()
QueryCurs.execute('SELECT * FROM Clients ORDER BY id DESC')
for i in QueryCurs:
print ("\n")
for j in i:
print (j)
QueryCurs.close()
master.mainloop()
我在测试代码时遇到此错误:
TypeError: AddEntry() missing 3 required positional arguments: 'Name', 'Street', and 'City'
我需要帮助 谢谢
答案 0 :(得分:0)
我通过此新代码修改功能“ AddEntry ”:
def AddEntry():
city_get=str(var_City.get())
name_get=str(var_Name.get())
street_get=str(var_Street.get())
QueryCurs.execute('''INSERT INTO Clients (Name,Street,City) VALUES (?,?,?)''',(name_get,street_get,city_get))
CreateDataBase.commit()
然后添加此新功能和按钮以显示数据库的内容。
btn_display_database=Button(master,text='display content of database', command=display_database)
btn_display_database.pack()
def display_database():
QueryCurs.execute('SELECT * FROM Clients ORDER BY id DESC')
for resultat in QueryCurs.fetchall():
print(resultat)
如果我不在脚本末尾之前编写脚本,则该脚本有效:master.mainloop() 这两个命令可关闭游标和连接:
QueryCurs.close()
CreateDataBase.close()
如果我写了最后两个命令,则在运行脚本时出现以下错误:
sqlite3.ProgrammingError: Cannot operate on a closed cursor