有人可以告诉我为什么下面的代码会抛出错误。它的目的是查看当前的id,如果它的最小值下降到数据库中的下一行并打印它。
def loadData(self):
connection = sqlite3.connect('films.db')
c = connection.cursor()
maxid_before = c.execute("SELECT * FROM FILMS WHERE ID = (SELECT MAX(ID) FROM FILMS)")
last_row = maxid_before.fetchone()[0]
maxid_after = c.execute("SELECT * FROM FILMS WHERE ID < (last_row) ORDER BY ID DESC LIMIT 1;").fetchone()
print(maxid_after)
更新 这是调用loadData的函数。这次我做了什么傻事。你可以忽略前5行左右。
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.edit_btn.clicked.connect(self.Retrieve)
self.edit_save_btn.clicked.connect(self.insertData)
last_id = 0
if not last_id:
connection = sqlite3.connect('films.db')
c = connection.cursor()
result = c.execute("SELECT * FROM FILMS WHERE ID = (SELECT MAX(ID) FROM FILMS)")
last_id = result.fetchone()[0]
self.edit_load_btn.clicked.connect(self.loadData)
这是loadData函数
def loadData(self, last_id):
connection = sqlite3.connect('films.db')
c = connection.cursor()
maxid_after = c.execute("SELECT * FROM FILMS WHERE ID < ? ORDER BY ID DESC LIMIT 1;", (last_id,)).fetchone()
print(maxid_after)
return maxid_after
答案 0 :(得分:1)
试试这个 -
maxid_after = c.execute("SELECT * FROM FILMS WHERE ID < ? ORDER BY ID DESC LIMIT 1;", (last_row,)).fetchone()
在您的代码last_row
中,变量不是列名。因此,您应该将last_row
的值放在查询中。
如果您像查询一样将last_row
放在查询中,sqlite会将last_row
视为列名并尝试执行此类查询。由于它无法通过该名称找到任何列,因此会抛出错误。
如果你想在按钮上运行这个功能,并在每次点击按钮时按降序逐行返回,那么你的功能应该是这样的 -
def loadData(self):
connection = sqlite3.connect('films.db')
c = connection.cursor()
result = c.execute("SELECT * FROM FILMS WHERE ID < ? ORDER BY ID DESC LIMIT 1;", (last_id,)).fetchone()
if result:
self.last_id = result[0]
connection.close()
调用loadData()
的函数应该像 -
# This is the code that calls loadData()
# This is __init__
result = c.execute("SELECT * FROM FILMS WHERE ID = (SELECT MAX(ID) FROM FILMS)").fetchone()
if result:
self.last_id = result[0]
...
# On button click
# Call loadData