title: Try / except statement causes sql query not to run properly
body: <p>I have a python script that pulls sql queries from a database but unfortunately the database has performance issue and sometime kills my script. My script loops through a .txt file to get the domain_name that is used in the sql query. I would like to implement try and except into my script so it will automatically continue retrying even when the connection to the database is lost momentarily. My code and error message is below and I would greatly appreciate your assistance!</p>
  
  <p><strong>Error message</strong>
  Traceback (most recent call last):
    File "2:38pm", line 63, in 
      connect_to_db()
    File "2:38pm", line 55, in connect_to_db
      pprint.pprint(unique_domains)
  UnboundLocalError: local variable 'unique_domains' referenced before assignment</p>
  
  <p><strong>Code</strong></p>
  
  <pre><code>from __future__ import print_function
  
  try:
      import psycopg2
  except ImportError:
      raise ImportError('\n\033[33mpsycopg2 library missing. pip install psycopg2\033[1;m\n')
      sys.exit(1)
  
  import re
  import sys
  import json
  import pprint
  
  outfilepath = "crtsh_output/crtsh_flat_file"
  
  DB_HOST = 'crt.sh'
  DB_NAME = 'certwatch'
  DB_USER = 'guest'
  
  conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST))
  cursor = conn.cursor()
  
  def connect_to_db():
      filepath = 'forager.txt'
      conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST))
      cursor = conn.cursor()
      with open(filepath) as fp:
          try:
              for cnt, domain_name in enumerate(fp):
                  print("Line {}: {}".format(cnt, domain_name))
                  print(domain_name)
                  domain_name = domain_name.rstrip()
  
  
                  cursor.execute('''SELECT c.id, x509_commonName(c.certificate), x509_issuerName(c.certificate), x509_notBefore(c.certificate), x509_notAfter(c.certificate), x509_issuerName(c.certificate), x509_k$
  FROM certificate c, certificate_identity ci WHERE
  c.id= ci.certificate_id AND ci.name_type = 'dNSName' AND lower(ci.name_value) =
  lower(%s) AND x509_notAfter(c.certificate) &gt; statement_timestamp()''',(domain_name,))
  
  
                  unique_domains = cursor.fetchall()
  
                  pprint.pprint(unique_domains)
  
                  outfilepath = "crtsh1" + ".json"
                  with open(outfilepath, 'a') as outfile:
                          outfile.write(json.dumps(unique_domains, sort_keys=True, indent=4, default=str, ensure_ascii = False))
  
          except:
              print("\n\033[1;31m[!] Unable to connect to the database\n\033[1;m")
  
  
  
  
          pprint.pprint(unique_domains)
  
          outfilepath = "crtsh1" + ".json"
          with open(outfilepath, 'a') as outfile:
                  outfile.write(json.dumps(unique_domains, sort_keys=True, indent=4, default=str, ensure_ascii = False))
  
  
  if __name__ == "__main__":
      connect_to_db()
  </code></pre>