sqlite 嵌套 for 循环错误

sqlite nested for loop bug

我正在尝试制作一个 ChatBot,但 运行 遇到了一个小问题。我在 python 中有一个嵌套或循环,它应该循环遍历一个包含其他 table 所有名称的 sqlite table。内部 for 循环循环遍历第一个循环中的 table,遍历单元格。

for i in c.execute("""SELECT * FROM triggers_sql"""):
    for l in c.execute("""SELECT * FROM "{}" """.format(i)):
        print(i, l)

但是,由于某种原因,外层 for 循环仅循环遍历第一个 table 的第一个单元格。我想不出我在这里做错了什么。

您需要使用两个单独的游标来做到这一点。游标代表单个结果集,内层c.execute()清除外层循环附加到游标的结果集。

如果 c 是连接对象,您需要从中显式创建游标:

outercursor = c.cursor()
for tablename, in outercursor.execute("SELECT tablename FROM triggers_sql"):
    innercursor = c.cursor()
    for row in innercursor.execute('SELECT * FROM "{}"'.format(tablename)):
        # ...

如果 c 是游标对象,只需从连接创建另一个。您甚至可以使用以下命令从现有游标执行此操作:

innercursor = c.connection.cursor()

请注意,可能有更好的方法来构建您的数据库,您不必首先使用动态 table 名称。将您现在使用单独 table 的所有内容存储在一个 table 中,并用一个额外的列替换 table 名称。那时你可以使用 JOIN 并将它留给 sqlite 来担心如何产生循环。