You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We need to make sure the connection and cursor is properly closed even if an exception is thrown.
Idea:
# ... other imports ...fromcontextlibimportclosingdefquery(db_name, sql):
"""Performs a database query and returns the result. It will uses contextlib to safely wrap a sqlite3 connection and a cursor to ensure the connection safely commits and closes (same as the cursor) in both happy and sad paths. Args: db_name (str): The name of the sqlite3 database to open. sql (str): The SQL query to perform. Returns: list: A list of tuples that gets returned by the performed query, as with calling ``cursor.fetchall()``. This will return an empty list in case nothing gets returned (such as for an UPDATE). """# Auto-closeswithclosing(sqlite3.connect(db_name)) asconn:
# Auto-commitswithconn:
# Auto-closeswithcontextlib.closing(conn.cursor()) ascur:
cur.execute(sql)
returncur.fetchall()
You can then use wrap this in the try...except block:
try:
# This will create a tuple that can be passed to the cursorquery_tuple="insert into Events values (?,?,?,?,?,?)", # .... query(DB_NAME, query_tuple)
exceptsqlite3.IntegrityErrorase:
logging.error(e)
This needs to be unit-tested as well.
The text was updated successfully, but these errors were encountered:
We need to make sure the connection and cursor is properly closed even if an exception is thrown.
Idea:
You can then use wrap this in the
try...except
block:This needs to be unit-tested as well.
The text was updated successfully, but these errors were encountered: