from tkinter import *
import psycopg2
# Db connection
try:
connection = psycopg2.connect(user="postgres",
password="admin",
host="192.168.1.9",
port="5432",
database="BigBearSystemsDB")
cursor = connection.cursor()
# Main window
window = Tk()
window.title("Big Bear Systems")
window.configure(background="light blue")
window.geometry("1500x950")
# Customer id
Label(window, text="Customer ID", bg="light blue", fg="black", font=("Ariel", 10)).grid(row=0, column=1, pady=5, padx=5, sticky=W)
# Customer name
Label(window, text="Customer name", bg="light blue", fg="black", font=("Ariel", 10)).grid(row=1, column=1, pady=5, padx=5, sticky=W)
# Active checkbox
Checkbutton(window, text="Active customer", bg="light blue", fg="black", font=("Ariel", 10)).grid(row=2, column=1, pady=5, padx=5, sticky=W)
# Customer id entry box
customerid = Entry(window, width=25, bg="white")
customerid.grid(row=0, column=2, sticky=W)
# Customer name entry box
customername = Entry(window, width=25, bg="white")
customername.grid(row=1, column=2, sticky=W)
# Save the customer to db function
def save_it():
Customerid = customerid.get()
Customername = customername.get()
cursor.execute('INSERT INTO customer(Customer ID, Customer name)VALUES (%s, %s)', (Customerid, Customername))
# Customer save button
Button(window, text="Save", width=14, command=save_it, font=("Ariel", 10)).grid(row=3, column=11, pady=250,padx=1,
sticky=E)
# Cancel function
def cancel():
window.destroy()
exit()
# Cancel button
Button(window, text="Cancel", width=14, command=cancel,font=("Ariel", 10)).grid(row=3, column=10, pady=250, padx=1, sticky=E)
connection.commit()
count = cursor.rowcount
print(count, "Record inserted successfully into table")
except (Exception, psycopg2.Error) as error:
if (connection):
print("Record failed to insert", error)
finally:
if (connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
window.mainloop()
Когда я выполняю приведенный ниже код для сохранения идентификатора клиента и имени клиента в базе данных, он пропускает функцию сохранения и переходит к исключению, а затем завершает работу.
Вот сообщение об ошибке, которое я получаю.
-1 Запись успешно вставлена в таблицу PostgreSQL соединение закрыто Исключение в обратном вызове Tkinter (последний вызов был последним): Файл "C: \ Users \ 13104 \ AppData \ Local \ Programs \ Python \ Python38-32 \ lib \ tkinter__init __. Py ", строка 1883, в call return self.fun c (* args) File" C: / Users / 13104 / PycharmProjects / BigBearSystems / BigBearSystemsUI.py ", строка 45, в save_it cursor.execute ('INSERT INTO customer (идентификатор клиента, имя клиента) VALUES (% s,% s)', (Customerid , Имя клиента)) psycopg2.InterfaceError: курсор уже закрыт
Процесс завершен с кодом выхода 0