如何仅从 tkinter 树视图更新选定的 sqlite3 记录 [英] How to update only selected sqlite3 record from tkinter treeview

查看:20
本文介绍了如何仅从 tkinter 树视图更新选定的 sqlite3 记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新 tkinter treeview 中选择的 sqlite3 db,我能够在 中插入 所选树视图的行entry 小部件但是当我更新所选的记录时,它会更新 sqlite3 数据库中的所有记录.我需要您的帮助才能更新 treeview 中选择的记录,而不是 sqlite3 数据库中的所有记录.

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()

推荐答案

这里的问题是你没有告诉数据库更新哪条记录:

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

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

所以所有记录都被更新了.您需要添加记录ID:

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')))

我在网站 https://www.tutorialspoint.com/sqlite/上找到了答案sqlite_update_query.htm.

这篇关于如何仅从 tkinter 树视图更新选定的 sqlite3 记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆