使用sqlite在python中使用cursor.execute和cursor.fetchall发出问题

时间:2013-04-17 03:28:27

标签: python sql database eclipse sqlite

我遇到的问题是在我的代码中将所有注释列表作为元组返回。这就是我所拥有的:

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),))

1 个答案:

答案 0 :(得分:2)

你有几个问题:

  1. 您没有对cursor.fetchall()
  2. 的结果做任何事情
  3. 您只返回第一个结果,而不是所有结果
  4. 我认为你需要的是:

    cursor.execute("SELECT * FROM comments")
    manyresults = cursor.fetchall()
    return list(manyresults)
    

    虽然你也可以这样做:

    return list(cursor.execute("SELECT * FROM comments"))