如何从数据库中删除或编辑记录

Posted

技术标签:

【中文标题】如何从数据库中删除或编辑记录【英文标题】:How do I delete or edit records from data base 【发布时间】:2021-08-06 16:30:25 【问题描述】:

我为我糟糕的英语提前道歉...... 我是编程界的新手,所以我真的不知道自己在做什么。我正在尝试用 Python,Tkinter 制作一个基本的通讯录。我设法以某种方式编写代码以在数据库中添加记录,但无法编写代码以删除或编辑选定的记录。帮助将不胜感激

import datetime
import tkinter
from tkinter import *
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import sqlite3


def date_for_humans():
    date = datetime.datetime.now().date()
    date = str(date)
    x = date.split("-")
    return x[2] + "." + x[1] + "." + x[0] + "."


# creating windows for show contact
def add():
    kontakti = Toplevel()
    kontakti.title("Lista kontakta")
    kontakti.iconbitmap(r"phonebookicon.ico")
    kontakti.geometry("400x500")
    kontakti.resizable(False, False)

    def submit():
        # create data base or connect to one
        conn = sqlite3.connect("Imenik.db")

        # create cursor
        c = conn.cursor()

        # insert into a table
        c.execute("INSERT INTO Kontakti VALUES (:f_name, :l_name, :number)",
                  
                    "f_name": f_name.get(),
                    "l_name": l_name.get(),
                    "number": number.get()
                  )

        # commint changes
        conn.commit()

        conn.close()

        f_name.delete(0,END)
        l_name.delete(0, END)
        number.delete(0, END)

    # creating and coloring top frame
    topframe = tk.Frame(kontakti, height=150, bg="#ffffff")
    topframe.pack(fill=X)

    # creating and coloring bottom farame
    bottomframe = tk.Frame(kontakti, height=350, bg="#34ebeb")
    bottomframe.pack(fill=X)

    # creating text at the top of app:
    text2 = Label(kontakti, text="DODAVANJE KONTAKTA", font="ariel 15 bold", bg="#ffffff", fg="black")
    text2.place(x=80, y=20)

    # creating close button
    button1 = Button(kontakti, text="Zatvori prozor", bg="white", fg="black",
                     activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=kontakti.destroy)
    button1.place(x=295, y=465)

    # create text boxes
    f_name = Entry(kontakti, width=30)
    f_name.place(x=80, y=200, height=20)
    l_name = Entry(kontakti, width=30)
    l_name.place(x=80, y=230, height=20)
    number = Entry(kontakti, width=30)
    number.place(x=80, y=260, height=20)

    # create text box labels
    f_name_label = Label(kontakti, text="Ime", bg="#34ebeb")
    f_name_label.place(x=20, y=200)
    l_name_label = Label(kontakti, text="Prezime", bg="#34ebeb")
    l_name_label.place(x=20, y=230)
    number_label = Label(kontakti, text="Broj", bg="#34ebeb")
    number_label.place(x=20, y=260)

    # create sumbit button
    submint_btn = Button(kontakti, text="Dodaj kontakt", bg="white", fg="black",
                         activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=submit)
    submint_btn.place(x=40, y=320)


def edit():

    c.execute("UPDATE Kontakti SET f_name=?, l_name=?, number=? WHERE f_name= ? AND l_name = ? AND number=?",
              (new_value_for_f_name, new_value_for_l_name, new_value_for_number, f_name, l_name, number))
    conn.commit()


def delete():

    f_name = listbox.curselection()[0]
    l_name = listbox.curselection()[1]
    number = listbox.curselection()[2]

    c.execute("DELETE * FROM Kontakti WHERE f_name = ? AND l_name = ? AND number = ?", (f_name, l_name, number))
    conn.commit()


def leave():
    root.destroy()


# creating a main window:
root = Tk()
root.title("Imenik App")
root.iconbitmap(r"phonebookicon.ico")
root.geometry("650x550")
root.resizable(False, False)

# creating and coloring top frame:
topFrame = tk.Frame(root, height=150, bg="#ffffff")
topFrame.pack(fill=X)


# creating and coloring bottom frame:
bottomFrame = tk.Frame(root, height=500, bg="#34ebeb")
bottomFrame.pack_propagate(False)
bottomFrame.pack(fill=X)

listbox = Listbox(bottomFrame)
listbox.place(x=40, y=40, height=340, width=200)
scrollbar = Scrollbar(bottomFrame)
scrollbar.place(height=340, x=240, y=40)

# Insert elements into the listbox

conn = sqlite3.connect("Imenik.db")
c = conn.cursor()
a = c.execute("SELECT *,oid FROM Kontakti")
records = c.fetchall()

for record in records:
    listbox.insert(END, str(record[0]) + " " + str(record[1]))

listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)

# creating text at the top of app:
text1 = Label(root, text="IMENIK", font="ariel 35 bold", bg="#ffffff", fg="black")
text1.place(x=240, y=40)

# displaying date and time at the top of app:

datel = Label(root, text="Danasnji datum: " + date_for_humans(), font="ariel 10 bold", bg="#ffffff", fg="black")
datel.place(x=450, y=125)

# displaying icon at the top of the app:
image1 = Image.open("phonebook1.png")
image1 = image1.resize((90, 90), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image1)
label1 = tkinter.Label(image=image, bg="#ffffff")
label1.image = image
label1.place(x=80, y=30)

conn.commit()
conn.close()


'''
# create data base or connect to one
conn = sqlite3.connect("Imenik.db")

# create cursor
c = conn.cursor()

# create table

c.execute("""CREATE TABLE kontakti (
        first_name txt,
        last_name txt,
        number integer
        )""")


# commint changes
conn.commit()

conn.close()
'''

# adding button 1, add contacts
viewButton = Button(root, text="Dodaj kontakt", pady=10, padx=70, bg="white", fg="black",
                    activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=add)
viewButton.place(x=380, y=200)

# adding button 2, edit contacts
addButton = Button(root, text="Izmeni kontakt", pady=10, padx=67, bg="white", fg="black",
                   activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=edit)
addButton.place(x=380, y=260)

# adding button 3, delete contacts
deleteButton = Button(root, text="Obrisi kontakt", pady=10, padx=70, bg="white", fg="black",
                      activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=delete)
deleteButton.place(x=380, y=320)

# adding button 4, exit button
exitButton = Button(root, text="Izlaz", pady=5, padx=50, bg="white", fg="black",
                    activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=leave)
exitButton.place(x=505, y=510)

root.mainloop()

如果有任何不清楚的地方,请询问我真的需要帮助。 提前致谢!

【问题讨论】:

你更新或删除的条件是什么? 如果您想从表中删除行,您需要一条 SQL delete 语句,您调用该语句的方式与您的代码执行 insert 的方式大致相同。 update 也是如此。 不要只是复制粘贴别人的代码而不理解他们的意思。 【参考方案1】:

您好,欢迎来到 Stack Overflow。为了让您知道鼠标选择了哪些数据,您可以使用以下方式:

name_of_listbox.curselection()

这将返回当前选定行的内容列表。它给了我们一个列表,因为有一个选项可以在ListBox 中选择多行数据。 您可以遍历每个并从中获取数据。 将数据存储在一个变量中,并将它们用于UPDATEDELETE 命令。

编辑:

删除记录:

f_name = listbox.curselection()[0]
l_name = listbox.curselection()[1]
number = listbox.curselection()[2]

c1.execute("DELETE * FROM Kontakti WHERE f_name = ? AND l_name = ? AND number = ?", (f_name, l_name, number))
conn1.commit()

用于修改值:

c1.execute("UPDATE Kontakti SET f_name=?, l_name=?, number=? WHERE f_name= ? AND l_name = ? AND number=?",(new_value_for_f_name,new_value_for_l_name,new_value_for_number, f_name, l_name, number))
conn1.commit()

我完全不明白您从单个列表框中选择名字、姓氏和数字的方式。所以我保持列表框的名称不变。

【讨论】:

感谢您的帮助,您能写出我的代码在我的情况下看起来如何吗?我会很感激 如果您觉得是最好的,请把我的回答设为最佳。谢谢:) 我很抱歉,但删除它给我这个错误:IndexError:元组索引超出范围。对于更新: NameError: name 'new_value_for_f_name' 未定义。我可能做错了什么,因为我说我是编程新手.. 如果有帮助,我将编辑我的问题并放入整个代码。 new_value_for_f_name 我的意思是你用来接受用户更新的新值的变量。其他人也一样。【参考方案2】:

您正在使用文字 sql 脚本,基本上您可以使用 deleteupdate,如下所示。

建议ORM (Object Relational Mapping) 比原始查询更轻松。

删除

DELETE <TableName> WHERE Id = <Value>

conn = sqlite3.connect("Imenik.db")
c = conn.cursor()
sql = "DELETE TableName WHERE Id = ?"
id = 1
c.execute(sql, (id,))

更新

UPDATE <TableName> SET <ColumnName> = <NewValue> WHERE Id = <Value>

conn = sqlite3.connect("Imenik.db")
c = conn.cursor()
sql = "UPDATE TableName SET ColumnName = ? WHERE Id = ?"
id = 1
new_value = 'hello'
# params order left to right (important).
c.execute(sql, (new_value, id))

【讨论】:

您需要在.execute():c.execute(sql, (id,))c.execute(sql, (new_value, id))中传递元组/列表中的值。 没错,现在修好了。感谢您的关注@acw1668 我可能是错的,但我认为这不会达到我想要的效果。让我尝试更好地解释。我已将数据库中的所有记录显示到列表框,我希望从那里能够删除或更新。例如,当我单击它时,我显示到列表框一条记录,它被选中,然后我想从那里创建按钮,该按钮将删除或打开新窗口以更新名称/姓氏/编号选择的记录。

以上是关于如何从数据库中删除或编辑记录的主要内容,如果未能解决你的问题,请参考以下文章

如何从mysql数据库中永久删除记录

如何获取隐藏的 ID 以删除 jQuery 数据表中的记录

PHP中如何在查询结果的每一条记录后加个编辑和删除按钮,实现编辑和删除操作。

即时插入/编辑

将记录移至存档视图 非软删除

如何确定正在删除哪些记录?