Referring to a python variable in SQLite3 DELETE statement

给你一囗甜甜゛ 提交于 2019-12-08 05:57:33

问题


I am writing a function to delete a record from a table. The variable I am trying to refer to in the delete statement is a Tkinter entry field.

I get the variable using the .get() method, but I can't then pass this into the SQLite statment without returning an error.

The following code is part of the frame, I've only added the relevant code to the problem

from tkinter import *

import sqlite3

class EditOrdersForm(Frame):

        def __init__(self):

        Frame.__init__(self)
        self.master.title("Edit Orders form:")
        self.pack()

        def displayDelOrderOptions(self):
            self.deleteOrderOptionsLabel = Label(self, text="Enter the Order ID of the order you wish to delete: ").grid(row=numOrders+4, pady=2, sticky=W)
            self.deleteOrderOptionsEntry = Entry(self, bd=3, width=10)
            self.deleteOrderOptionsEntry.grid(row=numOrders+4, pady=5, column=1)
            global orderToDelete
            orderToDelete = self.deleteOrderOptionsEntry.get()
            self.deleteButton = Button(self, text = "Delete this order", command = self.deleteOrder)
            self.deleteButton.grid(row=numOrders+5, pady=5, column=1)
        def deleteOrder(self):
            conn = sqlite3.connect("testdb.db")
            c = conn.cursor()

            c.execute("DELETE FROM orders WHERE orders_id=:1)", (orderToDelete,))

            conn.commit
            c.close()

root = EditOrdersForm()
root.mainloop()

The problem I have is with the WHERE statement, how do I refer to orderToDelete. I have tried converting it to a string and using (?) as the parameter but this didn't work either.


回答1:


THe correct syntax for parameterized query is:

c.execute("DELETE FROM orders WHERE orders_id=?)", (orderToDelete,))

I believe you just need to call commit instead of reference it

conn.commit()



来源:https://stackoverflow.com/questions/15972508/referring-to-a-python-variable-in-sqlite3-delete-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!