eid = None fid = None try: print self.cursor.mogrify( """SELECT * FROM emails AS e WHERE e.username = %(user)s AND e.hostname = %(host)s""", {'user': username, 'host': hostname} ) self.cursor.execute( """SELECT * FROM emails AS e WHERE e.username = %(user)s AND e.hostname = %(host)s""", {'user': username, 'host': hostname} ) except ProgrammingError: try: print self.cursor.mogrify( """INSERT INTO emails (username, hostname) VALUES (%(user)s, %(host)s) RETURNING id""", {'user': username, 'host': hostname} ) self.cursor.execute( """INSERT INTO emails (username, hostname) VALUES (%(user)s, %(host)s) RETURNING id""", {'user': username, 'host': hostname} ) except ProgrammingError: print("select fails, insert fails. WTF?!?") finally: try: eid = self.cursor.fetchone()[0] except ProgrammingError: print("nothing to fetch!") eid = -1 finally: print("email: %s" % eid) print("at the end, the eid: %s" % eid)