How to create a Cursur object that automatically closes using the with syntax in sqlite3 of the Python standard library.
If you use it normally, you need to write cur.close () while handling exceptions every time, which is very troublesome.
You can also use this to share code with psycopg2
, which has a similar API format.
import sqlite3
class AutoCloseCursur(sqlite3.Cursor):
def __init__(self, connection):
super().__init__(connection)
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
If you write it without such an implementation, the code will look like this:
with sqlite3.connect(DATABASE) as conn:
cur = conn.cursur()
cur.execute(SQL_QUERY)
cur.close()
conn.commit()
This has the following issues:
You can solve all three by using your own class as shown above.
with sqlite3.connect(DATABASE) as conn:
with AutoCloseCursur(conn)
cur.execute(SQL_QUERY)
conn.commit()
With a good combination, you will be able to handle PostgreSQL and SQLite DBs with the same code.
Recommended Posts