当第二个循环完成时,请有人解释为什么第一个循环会被退出。首先,我获得数据库中的所有表名(总计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相同的代码,只是没有持久的循环
#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我是否发现了错误,还是我只是个傻瓜?
发布于 2015-03-09 11:13:16
在获取第一个游标的结果之前,不应该在同一个游标中执行少量查询:
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)发布于 2015-03-09 11:28:48
单个游标对象一次只处理一个查询;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):
...注意:在对表的其他查询仍在运行时修改表是个坏主意。
https://stackoverflow.com/questions/28940354
复制相似问题