[英]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() ??
这是一个示例数据库和程序文件,可以进一步帮助我解释
我创建了变量来保存对组合框和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.