简体   繁体   中英

Python SQL query using variables

#Delete suspense window
class dWindow(QtGui.QMainWindow, Ui_dWindow):
    def __init__(self, parent = None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)

        for row in cursor.execute("SELECT FIRSTNAME FROM Staff"):
            self.comboUser.addItems(row)
        con.close()

        self.btnDeleteSuspense.clicked.connect(self.btnDeleteSuspense_Clicked)

    def btnDeleteSuspense_Clicked(self):
        user = self.comboUser.currentText() #finds selected user
        date = self.dateEdit.date().toString("M/d/yyyy")
        numrecord = cursor.execute() ??

Here is a sample DB and program file to further help me explain

程序样本

dbsample

I have created variables to hold the selection of the combobox and the dateEdit box.

The next step (the one I'm struggling with) is to then use those variables in an SQL query that will first find the count of rows with the selected user name and having a date <= than the selected date. That will populate the numrecord variable so that I can display a "This will delete 'x' rows, are you sure?"

If the user selects yes then I will then use the variable in a delete query to delete the selected rows.

I believe if I can figure out how to use the variables I have in a SQL query then the DELETE query should be rather simple.

An example of a possible DELETE query to show what I'm trying to do

cursor.execute("DELETE TO, count(*) FROM Suspense where TO = [user] and DATE = [date]")

I know that is wrong but maybe it will help clarify.

I hope I have explained my question fully and I appreciate any help provided.

Edit: Thanks so much!!

Just before I saw that you had posted this I figured it out.

What I came up with was the following:

qdate = self.dateTimeEdit.dateTime().toPyDateTime() #grabs the raw datetime from the QDateTimeEdit object and converts to python datetime

query = "SELECT DATE FROM Suspense WHERE DATE >= ?"  #creates the query using ? as a placeholder for variable

cursor.execute(query, (qdate,)) #executes the query and passes qdate as a tuple to the placeholder

With this knowledge I can recreate my queries to include both variables.

As mentioned in a comment to another answer, you should be using a proper parameterized query , for example:

# assumes that autocommit=False (the default)
crsr = conn.cursor()
sql = "DELETE FROM [Suspense] WHERE [TO]=? AND [DATE]<=?"
user = self.comboUser.currentText()  # as before
date = self.dateEdit.date()  # Note: no .toString(...) required
params = (user, date)
crsr.execute(sql, params)
msg = "About to delete {} row(s). Proceed?".format(crsr.rowcount)
if my_confirmation_dialog(msg):
    conn.commit()
else:
    conn.rollback()

What I came up with was the following:

qdate = self.dateTimeEdit.dateTime().toPyDateTime() #grabs the raw datetime from the QDateTimeEdit object and converts to python datetime

query = "SELECT DATE FROM Suspense WHERE DATE >= ?"  #creates the query using ? as a placeholder for variable

cursor.execute(query, (qdate,)) #executes the query and passes qdate as a tuple to the plac

With this knowledge I can now add both variables to the query as needed.

Thanks everyone for their help, especially Gord Thompson!

You use the DELETE sql command.

This assumes your DATE field is actually a date field and not a string field.

user = self.comboUser.currentText()
date = self.dateEdit.date().toString("yyyy-MM-dd")
cmd = "DELETE FROM Suspense WHERE TO = '{}' AND DATE >= '{}'".format(user, date)
cursor.execute(cmd)

Also, you may want to look into using an ORM framework ( sqlalchemy is probably the most popular, but there are others). It's best to avoid manually constructing sql queries if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM