Search code examples
pythonpostgresqlpsycopg2

psycopg2: How to know when cur.rowcount does not mean number of rows?


I'm looking for a way to programatically determine the difference between cur.rowcount describing the number of rows available to fetch versus the number of rows affected.

For example:

>>> cur.execute('CREATE TABLE test (gid serial, val numeric);')
>>> cur.execute('INSERT INTO test (val) values (1), (2), (3);')
>>> cur.execute('SELECT * FROM test;'); cur.rowcount
3
>>> cur.execute('UPDATE test SET val = 1;'); cur.rowcount
3
>>> cur.fetchall()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
psycopg2.ProgrammingError: no results to fetch

>>> cur.execute('DELETE FROM test;'); cur.rowcount
3

>>> cur.execute('DROP TABLE test;')
>>> cur.rowcount
-1

Using Python 2.7 and psycopg2 2.6.2.


Solution

  • According to the docs, cur.description will be None for operations without a result set.