Use Cursur that closes automatically with sqlite3 in Python

What is this

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.

Implementation

import sqlite3
class AutoCloseCursur(sqlite3.Cursor):
    def __init__(self, connection):
        super().__init__(connection)

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

How it will change

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:

  1. Difficult to read
  2. You need to explicitly close the cur
  3. From 2., the file stays open when an exception occurs

You can solve all three by using your own class as shown above.

Example of use

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

Use Cursur that closes automatically with sqlite3 in Python
How to use SQLite in Python
Use rospy with virtualenv in Python3
Use Python in pyenv with NeoVim
Use OpenCV with Python 3 in Window
Sqlite in python
Use various rabbimq features with pika in python
How to use tkinter with python in pyenv
Use Python in Anaconda environment with VS Code
Formulas that appear in Doing Math with Python
Use config.ini in Python
[Python] Use JSON with Python
Use dates in Python
Use Valgrind in Python
Use mecab with Python3
Use DynamoDB with Python
Use Python 3.8 with Anaconda
Use python with docker
Use profiler in Python
Specific sample code for working with SQLite3 in Python
String manipulation with python & pandas that I often use
Use Trello API with python
Use "$ in" operator with mongo-go-driver
Use let expression in Python
Scraping with selenium in Python
Use Measurement Protocol in Python
Working with LibreOffice in Python
Scraping with chromedriver in python
Use callback function in Python
Use Twitter API with Python
Use parameter store in Python
Debugging with pdb in Python
Use HTTP cache in Python
Use TUN / TAP with Python
Use sqlite3 with NAO (Pepper)
Use MongoDB ODM in Python
Working with sounds in Python
Use sqlite load_extensions with Pyramid
Use list-keyed dict in Python
Scraping with Selenium in Python
Use Random Forest in Python
Use regular expressions in Python
Scraping with Tor in Python
Use Spyder in Python IDE
Tweet with image in Python
Combined with permutations in Python
[Python] [SQLite3] Operate SQLite with Python (Basic)
Use subsonic API with python3
Let's create a script that registers with Ideone.com in Python.
Use a macro that runs when saving python with vscode
Automatically generate frequency distribution table in one shot with Python
How to log in to AtCoder with Python and submit automatically
Number recognition in images with Python
Use PointGrey camera with Python (PyCapture2)
Testing with random numbers in Python
Use vl53l0x with Raspberry Pi (python)
I want to use a wildcard that I want to shell with Python remove
GOTO in Python with Sublime Text 3
Working with LibreOffice in Python: import
Use fabric as is in python (fabric3)
CSS parsing with cssutils in Python