Psycopg2: How do I know when cur.rowcount does not mean the number of lines?

I am looking for a way to programmatically determine the difference between cur.rowcountdescribing the number of rows available for fetching and the number of rows affected.

For instance:

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

+4
source share
2 answers

According to docs there cur.description will be Nonefor operations without a set of results.

+1
source

, , rowcount DQL ( ) DML ( ) ( SELECT, UPDATE, DELETE ..). -1 DDL (Data Definition Language) - (CREATE, DROP, ALTER ..).

, , rowcount ( >= 0), ; / - rowcount = -1.

, fetchall(), EAFP - fetchall() ProgrammingError.

:

+2

Source: https://habr.com/ru/post/1663551/


All Articles