Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect whether to fetch from psycopg2 cursor or not?

Let's say if I execute the following command.

insert into hello (username) values ('me')

and I ran like

cursor.fetchall()

I get the following error

psycopg2.ProgrammingError: no results to fetch

How can I detect whether to call fetchall() or not without checking the query is "insert" or "select"?

Thanks.

like image 922
moeseth Avatar asked Jul 29 '16 11:07

moeseth


People also ask

What is cursor in Psycopg2?

The Cursor class of the psycopg library provide methods to execute the PostgreSQL commands in the database using python code. Using the methods of it you can execute SQL statements, fetch data from the result sets, call procedures. You can create Cursor object using the cursor() method of the Connection object/class.

What does cursor Fetchall () method do?

fetchall() Method. The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list. You must fetch all rows for the current query before executing new statements using the same connection.

Why is Psycopg used?

It is designed for multi-threaded applications and manages its own connection pool. Other interesting features of the adapter are that if you are using the PostgreSQL array data type, Psycopg will automatically convert a result using that data type to a Python list.

Is Psycopg2 thread safe?

Thread and process safety In DB API 2.0 parlance, Psycopg is level 2 thread safe. The difference between the above two approaches is that, using different connections, the commands will be executed in different sessions and will be served by different server processes.


3 Answers

Look at this attribute:

cur.description

After you have executed your query, it will be set to None if no rows were returned, or will contain data otherwise - for example:

(Column(name='id', type_code=20, display_size=None, internal_size=8, precision=None, scale=None, null_ok=None),)

Catching exceptions is not ideal because there may be a case where you're overriding a genuine exception.

like image 68
Chris B Avatar answered Oct 21 '22 17:10

Chris B


Check whether cursor.pgresult_ptr is None or not.

cursor.execute(sql)
if cursor.pgresult_ptr is not None:
    cursor.fetchall()
like image 28
itdv Avatar answered Oct 21 '22 16:10

itdv


The accepted answer using cur.description does not solve the problem any more. cur.statusmessage can be a solution. This returns SELECT 0 or INSERT 0 1. A simple string operation can then help determine the last query.

like image 21
Tirtha R Avatar answered Oct 21 '22 16:10

Tirtha R