开发者

In Python what could cause a for loop to randomly go backwards in value?

开发者 https://www.devze.com 2023-02-14 13:28 出处:网络
What can cause an iterator to go forwards in a loop, and then backwards? This is the code I\'m using to loop through the table\'s primary key field. The primary key is being used to populate initial

What can cause an iterator to go forwards in a loop, and then backwards?

This is the code I'm using to loop through the table's primary key field. The primary key is being used to populate initial values in a separate table.

For loop:

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

sqllite insert statement:

def insert_toTable(self, primaryKey, initial):
    c = self.conn.cursor()
    c.execute('insert into 开发者_StackOverflow中文版insert_toTable VALUES(?, ?)', (primaryKey, initial))
    if c.rowcount == 1:
        print "Updated row.\n"
    else:
        print "Row does not exist.\n"

    self.conn.commit()
    c.close()

The select statement that creates the tuple to loop through:

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

    c.close

    return c

Here is an example table:

Primary Key     Text
0               John
1               Sue
2               Bill
3               Tyler

Running the loop without the insert statement prints each unique key once, but if I add the call to the insert function (insert_toTable) I get this phenomenon:

0
Updated row.

1
Updated row.

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

The next iteration of the loop should be to the unique value "2" not back to "0"....

I can provide more sections of code if needed.


I suspect the results of this code may change depending on exactly which versions of sqlite and python are used.

Notice that your call to c.close in the select_fromTable method should be c.close(). This is a fortunate error, since you cannot iterate over the results of the query after the cursor is closed. However, the result is that you have two open cursors in the loop.

Try changing your select_fromTable method to:

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

and see what happens. I believe it will fix your problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号