在Python中,什么会导致for循环在值上随机倒退?

2024-07-03 07:06:21 发布

您现在位置:Python中文网/ 问答频道 /正文

什么会导致迭代器在循环中向前,然后向后?在

这是我用来遍历表的主键字段的代码。主键用于在单独的表中填充初始值。在

For循环:

for row in sampleDB.select_fromTable():
    print row[0]
    sampleDB.insert_toTable(row[0], 2.0)

sqllite插入语句:

^{pr2}$

创建要循环的元组的select语句:

def select_fromTable(self):
    c = self.conn.cursor()
    c.execute('select * from sampleTable')

    c.close

    return c

下面是一个示例表:

Primary Key     Text
0               John
1               Sue
2               Bill
3               Tyler

在不使用insert语句的情况下运行循环将打印每个唯一键一次,但是如果我将调用添加到insert函数(insert\U toTable),则会出现以下现象:

0
Updated row.

1
Updated row.

0
Traceback (most recent call last):
sqlite3.IntegrityError: column urlid is not unique

循环的下一次迭代应该是唯一值“2”,而不是返回到“0”。。。。在

如果需要,我可以提供更多的代码部分。在


Tags: 代码inselffor语句selectrowinsert
1条回答
网友
1楼 · 发布于 2024-07-03 07:06:21

我怀疑这段代码的结果可能会根据使用的sqlite和python的具体版本而改变。在

注意,在select_fromTable方法中对c.close的调用应该是c.close()。这是一个幸运的错误,因为您不能在游标关闭后迭代查询的结果。但是,结果是循环中有两个打开的游标。在

尝试将select_fromTable方法更改为:

def select_fromTable(self):
    c = self.conn.cursor()
    c.execute('select * from sampleTable')
    results = c.fetchall()
    c.close()
    return results

看看会发生什么。我相信它能解决你的问题。在

相关问题 更多 >