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.
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.
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.
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.
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.
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.
Check whether cursor.pgresult_ptr is None or not.
cursor.execute(sql)
if cursor.pgresult_ptr is not None:
cursor.fetchall()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With