I have the following method to setup a connection with the DB and tear it down in the end. Function looks something like this
def read_db(self, sql_statement):
conn = pymysql.connect(host=self.h,user=self.u,passwd=self.pw,
db=self.db,port=self.p)
try:
with conn.cursor() as cur:
cur.execute(sql_statement)
doStuffGeneratingException()
except Exception:
cur.rollback()
raise
finally:
conn.close()
Now if I had to replace this with context manager, I think it would look something like
@contextmanager
def setup_sql():
conn = pymysql.connect(host=self.h,user=self.u,passwd=self.pw,
db=self.db,port=self.p)
yield conn.cursor()
connection.cursor().close()
self.connection.close()
def read_db(self, sql_statement):
with setup_sql() as cur:
try:
cur.execute(sql_statement)
doStuffGeneratingException()
except:
cur.rollback()
raise
Now my questions are
- Is the above interpretation of context manager correct?
- If there was an error that occurred while doing
pymysql.connect(...)
statement insidecontextmanager
, how would that be handled? How would it be bubbled up to the calling function? - What happens if there is an exception in
doStuffGeneratingException()
in thewith
implementation? Will the control go first to thesetup_sql
to execute the statements afteryield
?