簡體   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() ??

這是一個示例數據庫和程序文件,可以進一步幫助我解釋

程序樣本

dbsample

我創建了變量來保存對組合框和dateEdit框的選擇。

下一步(我正在努力解決的問題)是在SQL查詢中使用這些變量,該查詢將首先查找具有所選用戶名且日期小於所選日期的行數。 這將填充numrecord變量,以便我可以顯示“這會刪除'x'行,確定嗎?”

如果用戶選擇是,那么我將在刪除查詢中使用該變量來刪除選定的行。

我相信,如果我能弄清楚如何使用SQL查詢中的變量,那么DELETE查詢應該相當簡單。

可能的DELETE查詢示例,以顯示我要執行的操作

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

我知道這是錯誤的,但也許會有助於澄清。

我希望我已經充分解釋了我的問題,並感謝您提供的任何幫助。

編輯:非常感謝!

在我看到您發布此消息之前,我已經弄清楚了。

我想到的是以下內容:

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

有了這些知識,我可以重新創建查詢以包括兩個變量。

如對另一個答案的評論中所述,您應該使用適當的參數化查詢 ,例如:

# 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

有了這些知識,我現在可以根據需要將兩個變量都添加到查詢中。

謝謝大家的幫助,尤其是Gord Thompson!

您使用DELETE 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)

另外,您可能想研究使用ORM框架( sqlalchemy可能是最受歡迎的框架,但是還有其他框架)。 如果可能的話,最好避免手動構造sql查詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM