import tkinter
from tkinter import *
import psycopg2
from tkinter import messagebox
t_conn={"dbname": "d1","user": "u1","password": "123qqq...A","port": "15400","host": "59.110.159.243"
}
try:conn=psycopg2.connect(**t_conn)
except psycopg2.Error as e:print("conn failed")
currsor=conn.cursor()
currsor.execute('''create table if not exists a2(id int,name varchar)''')def insert_db():id=insert_id_Entery.get()if id=="":print("输入为空")else:print("插入的id:",id)name=insert_name_Entry.get()if name=="":print("name不能为空")else:print("插入中")print("插入id对应的name值是:",name)result=messagebox.askokcancel("确认","确认插入吗")if result:currsor.execute(f"insert into a2 (id,name) values ('{id}','{name}')")messagebox.showinfo("信息","插入完成")conn.commit()print("插入成功")else:messagebox.showinfo("信息","取消插入")conn.rollback()
def delete_db():id=delete_id_Entry.get()if id=="":print("输入为空")else:print("删除中")print("删除的id:",id)result=messagebox.askokcancel("确认","确认删除吗")if result:currsor.execute(f"delete from a2 where id='{id}'")messagebox.showinfo("信息","删除完成")conn.commit()else:messagebox.showinfo("信息","取消删除")conn.rollback()
def update_db():id=update_id_Entry.get()if id=="":print("id不能为空")else:print("更新的id行是:",id)name=update_name_Entry.get()if name=="":print("name不能为空")else:print("更新中")print("更新id对应的name值是:",name)print("更新完成")result=messagebox.askokcancel("确认","确认更新吗")if result:currsor.execute(f"update a2 set name='{name}' where id='{id}'")messagebox.showinfo("信息","更新完成")conn.commit()else:messagebox.showinfo("信息","取消更新")conn.rollback()
def select_db():currsor.execute("select * from a2")row=currsor.fetchall()if row==[]:print("数据表为空")else:for i in row:print(i)
win=tkinter.Tk()
win.title('数据库增删改查')
insert_id_label=tkinter.Label(win,text="添加id值:")
insert_id_Entery=tkinter.Entry(win)
insert_name_label=tkinter.Label(win,text="添加name值:")
insert_name_Entry=tkinter.Entry(win)
insert_button=Button(win,text='增加',command=insert_db)
insert_id_label.grid(row=0,column=0)
insert_name_label.grid(row=1,column=0)
insert_id_Entery.grid(row=0,column=1)
insert_name_Entry.grid(row=1,column=1)
insert_button.grid(row=2,column=0,columnspan=2)
delete_id_label=tkinter.Label(win,text="删除id值:")
delete_id_Entry=tkinter.Entry(win)
delete_button=Button(win,text='删除',command=delete_db)
delete_id_label.grid(row=3,column=0)
delete_id_Entry.grid(row=3,column=1)
delete_button.grid(row=4,column=0,columnspan=2)
update_id_label=tkinter.Label(win,text="更新的id:")
update_id_Entry=tkinter.Entry(win)
update_name_label=tkinter.Label(win,text="更新id的name为:")
update_name_Entry=tkinter.Entry(win)
update_button=Button(win,text='修改',command=update_db)
update_id_label.grid(row=5,column=0)
update_id_Entry.grid(row=5,column=1)
update_name_label.grid(row=6,column=0)
update_name_Entry.grid(row=6,column=1)
update_button.grid(row=7,column=0,columnspan=2)
select_button=Button(win,text='查询结果',command=select_db)
select_button.grid(row=8,column=0,columnspan=2)
win.mainloop()
currsor.close()
conn.close()