Sqlite&;Python:退出for循环

Sqlite&;Python:退出for循环,python,sqlite,loops,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(t

有人能解释一下为什么第一个循环退出,而第二个循环完成了。 首先,我得到数据库中的所有表名(总共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

我是否发现了错误或我只是个傻瓜?

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

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)

单个游标对象一次只能处理一个查询<代码>执行()覆盖以前的任何结果

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

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):
        ...

注意:在表上的其他查询仍在运行时修改表是个坏主意。

什么是
tablename
content?
c
是数据库游标吗?在本例中,您正试图在同一个游标上嵌套多个查询。我明白了,以前从未真正知道游标的用途,但现在它有了意义。