0

How can I handle error like psycopg2.ProgrammingError:

   try
      cursor.execute("CREATE TEMP TABLE temp_table1 AS SELECT 11 as a, 22 as b, 'Count' as unit; DROP TABLE temp_table1;")
      data = cursor.fetchall()
   except psycopg2.ProgrammingError as e:
        if print(e) == "no result to fetch":
            print("Skip Error - {}".format(e)
        else:
            raise(e)

cursor has been created before.

e.pgerror is None.

if print(e) == "no result to fetch" doesn't work

I will be run different scripts with returned value and with doesn't. How can I handle the situation when the script returns nothing?

UPDATE: cursor.description is working way

   try
      cursor.execute("CREATE TEMP TABLE temp_table1 AS SELECT 11 as a, 22 as b, 'Count' as unit; DROP TABLE temp_table1;")
      if cursor.description:
            data = cursor.fetchall()
   except psycopg2.ProgrammingError as e:
        if print(e) == "no result to fetch":
            print("Skip Error - {}".format(e)
        else:
            raise(e)
Cherny
  • 21
  • 5
  • `print(e)` is going to return `None`, so `print(e) == "no result to fetch"` is always going to be false. Beyond that, I don't understand what you are asking with "how can I handle?" Your script can catch exceptions and then do whatever the language and reality allow. It's not clear what you want to happen in these cases. – Dennis Sparrow Jun 17 '20 at 06:52
  • @DennisSparrow Thanks for your note. I need to recognize `"no result to fetch"` and just skip it. If will be raised by other error need ti raise error. I updated code in my question. – Cherny Jun 17 '20 at 06:58
  • You could see if `e.diag.message_primary` contains anything useful. (I don't know anything about this module. I am just reading the documentation.) It also looks like you can check `cursor.description` before you call `cursor.fetchall()`. If the operation did not generate any result, `cursor.description` should be `None`. In that case, you could skip the call to `cursor.fetchall()` and avoid the exception. [A previous answer](https://stackoverflow.com/questions/38657566/detect-whether-to-fetch-from-psycopg2-cursor-or-not) suggested this, but a comment said it may not work. – Dennis Sparrow Jun 17 '20 at 07:20
  • @DennisSparrow Thanks a lot. `cursor.fetchall()` is working for me – Cherny Jun 17 '20 at 10:27

1 Answers1

1

cursor.description is working way

   try
      cursor.execute("CREATE TEMP TABLE temp_table1 AS SELECT 11 as a, 22 as b, 'Count' as unit; DROP TABLE temp_table1;")
      if cursor.description:
            data = cursor.fetchall()
   except psycopg2.ProgrammingError as e:
        if print(e) == "no result to fetch":
            print("Skip Error - {}".format(e)
        else:
            raise(e)
Cherny
  • 21
  • 5