Double insert into listbox SQLITE3 & TKINTER
In accordance with https://pynative.com/python-sqlite-insert-into-table/, you can also use following:
rows = cursor.fetchall()
instead of rows = cursor.execute("SELECT * FROM informations")
?
Then also close the cursor object afterwards with cursor.close()
.
Generally it,s also good to use a try-catch block around your CUD-operations , so you will be able to handle checked exceptions.
Hopefully, this will help!
It is because you forgot to clear the listbox list_1
before propagating data from the table:
def save_register(): firstname = entry_firstname.get() name = entry_name.get() adress = entry_adress.get() phone = entry_phone.get() connection = sql3.connect("gestionnaire.db") cursor = connection.cursor() cursor.execute("INSERT INTO informations ('FirstName', 'Name', 'Adress', 'Phone') VALUES (?,?,?,?)", (firstname, name, adress, phone)) connection.commit() list_1.delete(0, "end") # clear list_1 rows = cursor.execute("SELECT * FROM informations") for row in rows: list_1.insert(END, row)
Or just append the new record to list_1
:
def save_register(): firstname = entry_firstname.get() name = entry_name.get() adress = entry_adress.get() phone = entry_phone.get() connection = sql3.connect("gestionnaire.db") cursor = connection.cursor() cursor.execute("INSERT INTO informations ('FirstName', 'Name', 'Adress', 'Phone') VALUES (?,?,?,?)", (firstname, name, adress, phone)) connection.commit() # insert new record into list_1 list_1.insert(END, (cursor.lastrowid, firstname, name, adress, phone))
There is another issue in delete_register()
: it will remove all records in informations
table other than the selected record in list_1
. You need to add a WHERE
clause in the DELETE
SQL statement:
def delete_register(): index = list_1.curselection() if index: recid = list_1.get(index)[0] # get the unique ID of the selected record connection = sql3.connect("gestionnaire.db") cursor = connection.cursor() for row in index: cursor.execute("DELETE FROM informations WHERE id = ?", (recid,)) # delete selected record list_1.delete(row) connection.commit()