首页 > 解决方案 > Python + SQLite3 - 嵌套 For 循环

问题描述

在以下代码中,仅执行外部 for 循环的第一遍。一旦内部 for 循环完成一个完整的循环,外部 for 循环的后续循环就不会发生。有人可以帮我找出问题所在吗?

谢谢,拉吉

#!/usr/bin/python
import sqlite3

############################
#Create a comand object
############################
conn = sqlite3.connect('mxnet_sql.db')
c = conn.cursor()

#############################
#Do a select command
#############################
row1=[]
row2=[]
for row1 in c.execute('SELECT * FROM MIXED_NET_TABLE'):
    mnet_id = row1[0]
    mnet    = row1[1]
    for row2 in c.execute('SELECT * FROM AICM_TABLE'):
        mnet_aicm_id = row2[0]
        aicm         = row2[1]
        print("%s * %s" %(mnet_id, mnet_aicm_id))

print("When the inner fol loop complete the outer for loop does not run");

标签: pythonsqliteloopsfor-loop

解决方案


好的,我想我找到了一种更简单的方法-

  1. 要回答 po.pe 的问题,试试这个,是的,我确实被踢出了外循环;-)
  2. 对于肖恩的问题 - 在这样写的循环中 -

    对于 c.execute('SELECT * FROM MIXED_NET_TABLE') 中的行:mixed_net_table.append(row)

表的每一行都以元组的形式在“行”中返回。我随后在“mixed_net_table”中创建了一个元组数组。基本上我将SQL表读入python。在这种情况下,该表是二维的,可以通过通常的 mixed_net_table[row][col] 方式访问...


推荐阅读