1
我有問題將所有註釋列表作爲我的代碼中的元組返回。以下是我有:在python中使用sqlite使用cursor.execute和cursor.fetchall問題
def list_comments(db, limit=None):
"""return a list of all comments as tuples
- tuples are (id, useremail, page, comment)
if limit is provided it should be an integer and only that
many comments will be returned
"""
cursor.execute("SELECT * FROM comments")
manyresults = cursor.fetchall()
for row in cursor:
return row
那麼我現在要做的是從我的意見表中選擇的一切,返回它:
CREATE TABLE comments (
id integer unique primary key autoincrement,
useremail text,
page text,
comment text,
FOREIGN KEY(useremail) REFERENCES users(email)
);"""
我很新的這一切,所以如果我完全錯誤,請讓我知道我在做什麼錯了。謝謝!
編輯:這是一個測試,我跑這對
def test_list_comments(self):
"""The list_comments procedure should return a list of tuples
one for each of the comment entries in the database, each tuple
should contain """
clist = interface.list_comments(self.db)
# we should have the same number of comments as we created
self.assertEquals(len(clist), len(self.comments), "Wrong number of comments returned from list_units, expected %d, got %d" % (len(self.comments), len(clist)))
# comments should be in order so the largest id should be first
self.assertEquals(clist[0][0], self.comments[-1][0], "Wrong comment id first in comment list, expected %d, got %d" % (clist[0][0], self.comments[-1][0]))
# and the comment list should be ordered by id
ids = [c[0] for c in clist]
self.assertEqual(sorted(ids, reverse=True), ids, "List of comments returned is not in large-to-small order: %s" % (ids,))
# try the limit argument
clist = interface.list_comments(self.db, 3)
self.assertEquals(len(clist), 3, "Wrong number of comments returned from list_comments with a limit argument, expected 3, got %d" % (len(clist),))
哦,使得很多更有意義,我不知道爲什麼我沒有之前看到的。我仍然以某種方式使用我添加到原始問題描述中的測試來獲得異常錯誤。 – user2288946
self.assertEquals(clist [0] [0],self.comments [-1] [0],「錯誤的評論ID先在評論列表,預計%d,得到%d「%(clist [0] [0],self.comments [-1] [0])) AssertionError:錯誤的評論ID第一次在評論列表中,預期0,得到11 – user2288946
您需要添加'ORDER BY id'進行查詢,否則結果將不會按任何順序排序。 –