简体   繁体   English

使用变量的Python SQL查询

[英]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. 我创建了变量来保存对组合框和dateEdit框的选择。

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. 下一步(我正在努力解决的问题)是在SQL查询中使用这些变量,该查询将首先查找具有所选用户名且日期小于所选日期的行数。 That will populate the numrecord variable so that I can display a "This will delete 'x' rows, are you sure?" 这将填充numrecord变量,以便我可以显示“这会删除'x'行,确定吗?”

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. 我相信,如果我能弄清楚如何使用SQL查询中的变量,那么DELETE查询应该相当简单。

An example of a possible DELETE query to show what I'm trying to do 可能的DELETE查询示例,以显示我要执行的操作

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! 谢谢大家的帮助,尤其是Gord Thompson!

You use the DELETE sql command. 您使用DELETE sql命令。

This assumes your DATE field is actually a date field and not a string field. 假设您的DATE字段实际上是日期字段,而不是字符串字段。

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). 另外,您可能想研究使用ORM框架( sqlalchemy可能是最受欢迎的框架,但是还有其他框架)。 It's best to avoid manually constructing sql queries if possible. 如果可能的话,最好避免手动构造sql查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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