如何判断pysqlite 2.6.3中的更新语句是否成功

时间:2013-02-09 23:03:01

标签: python sqlite pysqlite

我使用pysqlite与SQLite数据库进行通信,我想知道检查UPDATE SQL语句是否实际上已成功更新表中某些内容的正确方法。< / p>

我是否可以在pysqlite执行此操作后快速检查变量?

1 个答案:

答案 0 :(得分:8)

检查cursor.rowcount属性;它会指出受影响的行数。

如果UPDATE未成功,则rowcount将为0:

>>> conn = sqlite3.connect(':memory:')
>>> conn.execute('CREATE TABLE foo (bar, baz)')
<sqlite3.Cursor object at 0x1042ab6c0>
>>> conn.execute('INSERT INTO foo VALUES (1, 2)')
<sqlite3.Cursor object at 0x1042ab730>
>>> cursor = conn.cursor()
>>> cursor.execute('UPDATE foo SET baz=3 WHERE bar=2')
<sqlite3.Cursor object at 0x1042ab6c0>
>>> cursor.rowcount
0
>>> cursor.execute('UPDATE foo SET baz=3 WHERE bar=1')
<sqlite3.Cursor object at 0x1042ab6c0>
>>> cursor.rowcount
1

当然,如果您尝试更新不存在的表或列,则会引发异常:

>>> cursor.execute('UPDATE nonesuch SET baz=3 WHERE bar=2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
sqlite3.OperationalError: no such table: nonesuch
>>> cursor.execute('UPDATE foo SET nonesuchcolumn=3 WHERE bar=2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
sqlite3.OperationalError: no such column: nonesuchcolumn

我使用Python附带的sqlite3 library来演示这个;在Python 2.5中,pysqlite2以该名称添加到Python中。差异仅仅是导入:

try:
    import sqlite3  # included library
except ImportError:
    from pysqlite2 import dbapi2 as sqlite3  # use pysqlite2 instead