3

I'm using pysqlite to talk to a SQLite db, and I wonder what is the right way to check whether an UPDATE SQL statement has actually successfully update something in a table.

Is there a variable I can quickly check after the execution for this in pysqlite?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
MLister
  • 10,022
  • 18
  • 64
  • 92

1 Answers1

10

Check the cursor.rowcount attribute; it'll indicate the number of affected rows.

If an UPDATE was not successful the rowcount will be 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

Of course, if you try to update a table or column that doesn't exist, an exception is thrown instead:

>>> 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

I used the sqlite3 library included with Python to demo this; pysqlite2 was added to Python under that name in Python 2.5. The difference is merely the import:

try:
    import sqlite3  # included library
except ImportError:
    from pysqlite2 import dbapi2 as sqlite3  # use pysqlite2 instead
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    I would take unsuccesful to mean "failed" - rather than just didn't update anything... – Jon Clements Feb 09 '13 at 23:22
  • Exactly what I mean - just because something doesn't affect any rows, doesn't mean it was unsuccessful :) It succeeded and didn't actually do anything!? – Jon Clements Feb 09 '13 at 23:23
  • @JonClements: It's the OP asking for a variable that made me assume it was about non-matching rows, really. The exception is kinda obvious, I'd say. – Martijn Pieters Feb 09 '13 at 23:25