插入SQLite数据库的行数为负
我正在尝试通过 Python
代码向 SQLite
数据库插入新记录。
con = sqlite.connect(connectionString)
cur = con.cursor()
countOfNewItems = 0
for ...
try:
con.execute("insert or ignore into items ...")
countOfNewItems += cur.rowcount
except:
cur.close()
con.close()
print "Error when inserting item '%s' to database." % item
exit(1)
cur.close()
con.commit()
con.close()
print "%d new items have been inserted." % countOfNewItems
我的代码报告插入的记录数是负数(-5141)。
因为我的数据库是空的,所以我可以通过命令行查看插入了多少记录。
select count(*) from items;
结果是4866。
你能告诉我哪里出问题了吗?为什么这两个值不一致,为什么会是负数?
2 个回答
4
http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.rowcount
虽然sqlite3模块中的Cursor类实现了这个属性,但数据库引擎在判断“受影响的行数”或“选中的行数”时的表现有点奇怪。
还有
根据Python数据库API规范,rowcount属性的值“在没有对游标执行任何executeXX()操作时为-1,或者最后一次操作的行数无法通过接口确定时也为-1”。
3
试试用 cur.execute
来代替 con.execute
。这样的话,cur.rowcount
就会在我简单插入数据时返回 1。