使用变量的Python SQL查询

2024-10-01 13:45:35 发布

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

#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() ??

下面是一个示例数据库和程序文件,以进一步帮助我解释

programsample

dbsample

我已经创建了一些变量来保存组合框和日期编辑框的选择。在

下一步(我正在努力解决的问题)是在一个SQL查询中使用这些变量,该查询将首先查找具有所选用户名且日期比所选日期<;=的行数。这将填充numrecord变量,这样我就可以显示“这将删除'x'行,确定吗?”在

如果用户选择yes,那么我将使用delete查询中的变量来删除所选的行。在

我相信如果我能弄清楚如何使用SQL查询中的变量,那么DELETE查询应该相当简单。在

一个可能的DELETE查询的示例,以显示我正在尝试执行的操作

^{pr2}$

我知道这是错误的,但也许这有助于澄清。在

我希望我已经充分地解释了我的问题,我感谢你提供的任何帮助。在

编辑:非常感谢!!在

就在我看到你把这个贴出来之前,我想出来了。在

我想到的是:

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

有了这些知识,我可以重新创建查询以包含这两个变量。在


Tags: theselfforexecuteinitdefquerycursor
3条回答

使用^{}sql命令。在

这假设您的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)

{其他人可能也希望使用^ a2框架。如果可能,最好避免手动构造sql查询。在

如另一个答案的注释中所述,您应该使用适当的参数化查询,例如:

# 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()

我想到的是:

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

有了这些知识,我现在可以根据需要将这两个变量添加到查询中。在

感谢大家的帮助,尤其是戈德·汤普森!在

相关问题 更多 >