Sqlite& Python:退出循环

时间:2015-03-09 11:00:06

标签: python sqlite loops

有人可以解释为什么第一个循环退出,第二个循环完成时。 首先我得到数据库中的所有表名(共4个结果) 然后我想从该表中获取所有数据。

但我只是出于某种原因从第一张表中获取数据。 如果我删除从表中获取数据的循环,那么它会一直运行第一个for循环。

#Get all tables in database file
for tablename in c.execute("SELECT name FROM sqlite_master WHERE type='table';"):
    print(tablename[0])

    for elementdate in c.execute('SELECT * FROM %s ORDER BY Date DESC' % tablename[0]):
        print(elementdate)

Output:
table_1
(1, '20120210', 360)
(2, '20100210', 204)
Loop Excited

相同的代码,没有last for循环

#Get table names
for tablename in c.execute("SELECT name FROM sqlite_master WHERE type='table';"):
    print(tablename[0])

    #for elementdate in c.execute('SELECT * FROM %s ORDER BY Date DESC' % tablename[0]):
    #   print(elementdate)

Output:
table_1
table_2
table_3
table_4
Loop Excited

我发现了一个错误,还是我只是愚蠢?

2 个答案:

答案 0 :(得分:2)

在获取第一个结果之前,您不应该在同一个游标中执行少量查询:

c.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = c.fetchall()
for tablename in tables:
    print(tablename[0])
    c.execute('SELECT * FROM %s ORDER BY Date DESC' % tablename[0])
    for elementdate in c.fetchall():
        print(elementdate)

答案 1 :(得分:1)

单个游标对象一次只能使用一个查询; execute()会覆盖以前的所有结果。

如果要同时执行两个查询,请使用两个游标:

c = db.cursor()
c2 = db.cursor()
for row in c.execute("SELECT name FROM sqlite_master WHERE type='table'"):
    tablename = row[0]
    for row2 in c2.execute("SELECT * FROM %s ORDER BY Date DESC" % tablename):
        ...

注意:修改表格是一个坏主意,而其他一些查询仍然在运行。