我使用pysqlite
与SQLite数据库进行通信,我想知道检查UPDATE
SQL语句是否实际上已成功更新表中某些内容的正确方法。< / p>
我是否可以在pysqlite
执行此操作后快速检查变量?
答案 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