How to update only selected sqlite3 record from tk

2019-09-02 11:54发布

Am trying to update sqlite3 db selected in tkinter treeview, am able to insert the row of the treeview selected in the entry widget but when i update the record selected it updates all the records in the sqlite3 db. I need your help to update only the record selected in the treeview but not all the records in the sqlite3 db.

from tkinter import ttk
import tkinter as tk
import sqlite3


def connect():
    conn = sqlite3.connect("TRIAL.db")
    cur = conn.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS profile(id INTEGER PRIMARY KEY, 
First TEXT, Surname TEXT)")
    conn.commit()
    conn.close()


def Update():
    data1 = first_text.get()
    data2 = surname_text.get()

    for selected in tree.selection():
        e1.insert(0, selected) 
        e2.insert(0, selected)
        conn = sqlite3.connect("TRIAL.db")
        cur = conn.cursor()
        cur.execute("UPDATE profile SET First=?, Surname=?", (data1, data2))
        conn.commit()
        conn.close()


def get_selected_row(event):
    print(tree.selection())  # this will print the names of the selected rows
    for nm in tree.selection():
        content = tree.item(nm, 'values')
        e1.insert(tk.END, content[1])
        e2.insert(tk.END, content[2])  # this will insert in the entry after

connect()  #  this to create the db

root = tk.Tk()
root.geometry("400x400")
                          # this will hide the first column
tree= ttk.Treeview(root, column=("column1", "column2", "column3"), 
show='headings')
tree.heading("#1", text="NUMBER") 
tree.heading("#2", text="FIRST NAME")
tree.heading("#3", text="SURNAME")
tree.pack()

tree.bind("<<TreeviewSelect>>", get_selected_row)

first_text = tk.StringVar()
e1 = tk.Entry(root, textvariable=first_text)
e1.pack()
surname_text = tk.StringVar()
e2 = tk.Entry(root, textvariable=surname_text)
e2.pack()

b2 = tk.Button(text="EDIT PARTICULAR DATA", command=Update)
b2.pack(side=tk.BOTTOM)

root.mainloop()

1条回答
爷的心禁止访问
2楼-- · 2019-09-02 12:16

The issue here is that you don't tell the db which record to update:

cur.execute("UPDATE profile SET First=?, Surname=?", (data1, data2)) 

so all records are updated. You need to add the record id:

cur.execute("UPDATE profile SET First=?, Surname=?  WHERE ID =?", (data1, data2, tree.set(selected, '#1')))

I found the answer on the website https://www.tutorialspoint.com/sqlite/sqlite_update_query.htm.

查看更多
登录 后发表回答