我按如下方式创建一个简单的SQLite表:
import sqlite3
sqlite_file = '/Users/Dom/Desktop/Test.sqlite'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
c.execute('''CREATE TABLE Results(Col1 text, Col2 text)''')
c.execute('''CREATE TABLE ListIDTable(Int numeric, ID text)''')
values_to_insert = [(1,"1a"), (2,"1b"), (3,"2a"), (4,"2b"), (5,"3a"),
(6,"3b"), (7,"4a"), (8,"4b"), (9,"5a"), (10,"5b"), (11,"6a"), (12,"6b"),
(13,"7a"), (14,"7b") ]
c.executemany("INSERT INTO ListIdTable (Int, ID) values (?,?)",
values_to_insert)
conn.commit()
conn.close()
一切看起来都不错。 然后我按如下方式遍历上面创建的表:
import sqlite3
sqlite_file = '/Users/Dom/Desktop/Test.sqlite'
conn = sqlite3.connect(sqlite_file)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c2 = conn.cursor()
c.execute('select * from ListIDTable ORDER BY Int ASC')
for r in c:
TblInt = r['Int']
print (TblInt)
c2.execute("INSERT INTO Results (Col1 , Col2) values (?,?)", ("XXX",
"YYY"))
conn.commit()
我希望输出: " 1,2,3,4,5,6 ......"等
然而,我得到: " 1,2,1,2,3,4,5,6 ......"等
当我删除最后conn.commit()语句的缩进时,我得到了预期的输出。 有人可以帮助我理解为什么只是" 1& 2"重复,但一切都正常进行?
由于
答案 0 :(得分:0)
以下页面确定并解释了该问题: Using multiple cursors in a nested loop in sqlite3 from python-2.7
为了解决上述问题,我基本上完成了整个查找表并消除了对多个游标的需求:
import sqlite3
sqlite_file = '/Users/Dom/Desktop/Test.sqlite'
conn = sqlite3.connect(sqlite_file)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('select * from ListIDTable ORDER BY Int ASC')
rows = c.fetchall()
for r in rows:
TblInt = r['Int']
print (TblInt)
c.execute("INSERT INTO Results (Col1 , Col2) values (?,?)", ("XXX",
"YYY"))
conn.commit()