我尝试更新sqlite3
中选择的tkinter treeview
数据库,我可以在row of the treeview selected
小部件中插入entry
但是当我更新所选的记录时,它会更新所有sqlite3
db中的记录。我需要您的帮助才能更新treeview
中选择的记录,但不更新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()
答案 0 :(得分:0)
这里的问题是你没有告诉db要更新哪条记录:
cur.execute("UPDATE profile SET First=?, Surname=?", (data1, data2))
所以所有记录都会更新。您需要添加记录ID:
cur.execute("UPDATE profile SET First=?, Surname=? WHERE ID =?", (data1, data2, tree.set(selected, '#1')))
我在网站https://www.tutorialspoint.com/sqlite/sqlite_update_query.htm找到了答案。