pythonpsycopg2

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.


Solution

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