I'm going through a database with python and using try
and except
a lot to handle queries. In trying to optimize my code, I've hit a weird bump.
This code:
try:
cursor.execute("SELECT my_name FROM {}.{} LIMIT 1".format(myschema,mytable))
except(Exception, psycopg2.DatabaseError) as error:
conn.rollback()
else:
origName = cursor.fetchone()
if origName is None:
outputName = "ERROR2"
return outputName
try:
cursor.execute("SELECT different_column FROM {}.{} ORDER by a_column DESC LIMIT 1".format(myschema, mytable))
except(Exception, psycopg2.DatabaseError) as error:
conn.rollback()
try:...
#more try/excepts and so on
takes about 19 minutes to run through the entire data warehouse.
but THIS code:
try:
cursor.execute("SELECT my_column FROM {}.{} LIMIT 1".format(myschema,mytable))
except(Exception, psycopg2.DatabaseError) as error:
conn.rollback()
origName = cursor.fetchone()
if origName is None:
outputName = "ERROR2"
return outputName
try:
cursor.execute("SELECT different_column FROM {}.{} ORDER by a_column DESC LIMIT 1".format(myschema, mytable))
except(Exception, psycopg2.DatabaseError) as error:
conn.rollback()
try:...
#exact same code with try/excepts and so on
literally completes running in about 1-1.5 minutes. Why is it so much faster if I remove that else? Is something being skipped/ignored? I feel like I must be doing wrong. I don't really understand how to just continue with my code after a try:except:
statement.