为什么此更新查询无法在Python中运行?

时间:2018-01-15 14:41:22

标签: python database sqlite

所以我正在创建一个利用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

1 个答案:

答案 0 :(得分:1)

你必须明确地提交事务(大多数客户端程序为你自动执行它而不是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

最后,打开一个连接不是免费的,所以最好尽可能长时间打开它,而不是在每次操作时打开/关闭它。