为什么这个更新查询在Python中不起作用?

2024-04-25 01:32:02 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我正在创建一个利用SQLite数据库的商店管理系统。 当我直接在SQLite浏览器中执行查询时,它可以工作,但是当我使用Python时,没有错误,但是更新没有发生。你能看一下吗。你知道吗

我用剩余库存更新的部分:

value1 = int(self.stock) - int(self.qne.get()) 
sql = "UPDATE products SET stock = " + str(value1) + " WHERE pk = " + str(self.ident.get())
conn.execute(sql)
conn.close()

我到目前为止的完整代码:

# import random
from tkinter import *
import datetime
import sqlite3

conn = sqlite3.connect('database.db')

products_list = []
quantity_list = []
price_list = []
class Application:
    def __init__(self, master):
        self.master = master
        # today's date
        date = datetime.datetime.now()
        # frames
        self.left = Frame(master, width=800, height=700, bg='white')
        self.left.pack(side=LEFT)

        self.right = Frame(master, width=400, height=700, bg='steelblue')
        self.right.pack(side=RIGHT)

        # heading
        self.heading = Label(self.left, text="Welcome to Store Management System", font=('arial 40 bold'), fg='steelblue', bg='white')
        self.heading.place(x=0, y=0)

        # cart
        self.cart = Label(self.right, text=("TEST TRADE LINK"), font=('arial 25 bold'), fg='white', bg='steelblue', padx=10, pady=10)
        self.cart.place(x=0, y=0)

        # datelabel
        self.datelabel = Label(self.right, text= (str(date)[:10]), font=('arial 25 bold'), fg='white', bg='steelblue')
        self.datelabel.place(x=0,y=55)

        # template for bill
        self.bpro = Label(self.right, text= "Products", font=('arial 16 bold'), fg='white', bg='steelblue')
        self.bpro.place(x=0, y=100)

        self.bqua = Label(self.right, text= "Quantity", font=('arial 16 bold'), fg='white', bg='steelblue')
        self.bqua.place(x=120, y=100)

        self.bpri = Label(self.right, text= "Price", font=('arial 16 bold'), fg='white', bg='steelblue')
        self.bpri.place(x=240, y=100)


        # label for the input
        self.id = Label(self.left, text="Enter Unique ID", font=('arial 16 bold'), bg='white')
        self.id.place(x=0, y=80)

        # entry for the unique id
        self.inp = IntVar()
        self.ident = Entry(self.left, width=50, bg='white', textvariable=self.inp)
        self.ident.place(x=190, y=82)

        # button
        self.submit = Button(self.left, text="Submit", width=17, height=2, command=self.ajax)
        self.submit.place(x=400, y=125)

        # ajax contents
        self.products_name = Label(self.left, text="", font=('arial 16 bold'), bg='white')
        self.products_name.place(x=0, y=250)

        self.price = Label(self.left, text="", font=('arial 16 bold'), bg='white')
        self.price.place(x=0, y=290)

        self.expiration = Label(self.left, text="", font=('arial 16 bold'), bg='white')
        self.expiration.place(x=0, y=330)

        # down reached upto y=440
        self.total = Label(self.left, text="", font=('arial 16 bold'), bg='white')
        self.total.place(x=0, y=480)
    def ajax(self):
        if self.ident.get() == "0":
            print("Failed")
        else:
            self.result = conn.execute("SELECT * FROM products WHERE pk LIKE ?", [str(self.ident.get())])
            for self.row in self.result:
                self.product = self.row[1]
                self.expd = self.row[4]
                self.cost = self.row[3]
                self.stock = self.row[2]
                self.products_name.configure(text="Product Name: " + str(self.product))
                self.price.configure(text="Price Per Unit: Rs. " + str(self.cost) + " \t")
                self.expiration.configure(text="Expiration Date: " + str(self.expd))

                # new labels and entries
                self.qn = Label(self.left, text="Quantity", font=('arial 16 bold'), bg='white')
                self.qn.place(x=0, y=370)

                self.q = IntVar()
                self.qne = Entry(self.left, width=50, bg='white', textvariable=self.q)
                self.qne.place(x=150, y=371)

                self.discount = Label(self.left, text="Discount", font=('arial 16 bold'), bg='white')
                self.discount.place(x=0, y=410)

                self.d = IntVar()
                self.dise = Entry(self.left, width=50, bg='white', textvariable=self.d)
                self.dise.place(x=150, y=410)

                self.btnadd = Button(self.left, width=17, height=2, text="Add to Cart", bg='lightblue', command=self.add_to_cart)
                self.btnadd.place(x=400, y=440)

                self.bill = Button(self.left, width=17, height=2, text='Generate Bill', bg='lightgreen', command=self.print_bill)
                self.bill.place(x=200, y=440)
    def add_to_cart(self):
        products_list.append(self.product)
        quantity_list.append(self.qne.get())
        price_list.append(int(self.qne.get()) * int(self.cost))

        value1 = int(self.stock) - int(self.qne.get()) 
        sql = "UPDATE products SET stock = " + str(value1) + " WHERE pk = " + str(self.ident.get())
        conn.execute(sql)
        conn.close()
        t = 150
        i = 0
        for p in products_list:
            self.pr1 = Label(self.right, text=str(products_list[i]), font=('arial 16 bold'), bg='steelblue', fg='white').place(x=0, y=t)
            self.pr2 = Label(self.right, text=(str(quantity_list[i])), font=('arial 16 bold'), bg='steelblue', fg='white').place(x=120, y=t)
            self.pr3 = Label(self.right, text=(str(price_list[i])), font=('arial 16 bold'), bg='steelblue', fg='white').place(x=240, y=t)
            t += 40
            i += 1

        print(str(products_list) + str(quantity_list)+ str(price_list))
    def print_bill(self):
        f = open("bill.txt", 'w+')
        f.write(str(products_list) + str(quantity_list) + str(price_list))
        f.close()

        # reset all after each purchase
        # delete the temporary cart
        del(products_list[:])
        del(quantity_list[:])
        del(price_list[:])

        # # delete the labels
        # self.pr1.configure(text="")
        # self.pr2.configure(text="")
        # self.pr3.configure(text="")
root = Tk()
b = Application(root)
# root.resizable(False, False)
root.geometry("1200x720+0+0")

root.mainloop()

我的第一个产品有50,我正在尝试更新它,但当我检查后,更新执行,它显示50。你知道吗

我的数据库:

Here is the image of my database


Tags: textselfrightplaceleftlabellistproducts
1条回答
网友
1楼 · 发布于 2024-04-25 01:32:02

您必须明确地提交事务(大多数客户端程序自动地为您提交事务,但db api模块除外):

value1 = int(self.stock) - int(self.qne.get()) 
sql = "UPDATE products SET stock = " + str(value1) + " WHERE pk = " + str(self.ident.get())
conn.execute(sql)
conn.commit()
conn.close()

不相关,但以这种方式构造sql查询不仅容易出错(尤其是转义问题),而且a huge security issue that leaves your code opened to SQL injections。你知道吗

相反,您希望使用游标并让db api负责正确构建查询:

value = int(self.stock) - int(self.qne.get()) 
id = self.ident.get()
sql = "UPDATE products SET stock=? WHERE pk=?"
cursor = conn.cursor()
cursor.execute(sql, (value, id))
conn.commit()

这个和commit()调用实际上是well documented

最后,打开连接并不是免费的,因此最好尽可能长时间地保持连接打开,而不是每次操作都打开/关闭连接。你知道吗

相关问题 更多 >