[英]How to update only selected sqlite3 record from tkinter treeview
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. 我正在尝试更新在
tkinter treeview
选择的sqlite3
db,能够插入在entry
小部件中row of the treeview selected
的row of the treeview selected
但是当我更新所选记录时,它将更新sqlite3
db中的所有记录。 I need your help to update only the record selected in the treeview
but not all the records in the 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()
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:
您需要添加记录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 . 我在网站https://www.tutorialspoint.com/sqlite/sqlite_update_query.htm上找到了答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.