Does python sqlite3 need to turn on and off every operation it performs?

when I first came into contact with the database, I was not proficient in many operations. I encountered some doubts as follows:

the version of python used is 3.6

Code first:

import sqlite3
from pathlib import Path

def open_db():
    root = Path(__file__).parent.parent
    db_path = str(root / "db/data.sqlite")
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    return conn, cursor

def close_db(conn, cursor):
    conn.commit()
    cursor.close()
    conn.close()

class User:

    def __init__(self, form):
        self.username = form.get("username", "")
        self.password = form.get("password", "")
    
    @classmethod
    def add(cls, user):
        conn, cursor = open_db()
        sql_insert = """
        INSERT INTO
            User(xxx)
        VALUES
            (xxx);
        """
        conn.execute(sql_insert)
        close_db(conn, cursor)
        
    @classmethod
    def update(cls, id, password):
        conn, cursor = open_db()
        sql_update = """
        UPDATE
            `User`
        SET
            `email`=?
        WHERE
            `id`=?
        """
        conn.execute(sql_update, (id, password))
        close_db(conn, cursor)

there are two functions open_db and close_db to open and close the database, and the User class has two class methods add and update to add and update records. The problem now is that every time I write a method about database operation, it is very troublesome to call it. Is there a simpler way to operate?

I have the knowledge of database for the first time. Please forgive me if there is any deficiency. I sincerely hope that all the seniors can give us an answer. I would appreciate it.

Jun.08,2022

there seems to be no answer to this question for a few days. I'll answer it myself. There may be mistakes in the solution, and please point out

in time.

1, use with

the document says:

Connection objects can be used as context managers that automatically commit or rollback transactions. In the event of an exception, the transaction is rolled back; otherwise, the transaction is committed:

roughly means that the connected database object can be automatically committed or rolled back as a context manager, so the code is roughly as follows:

  https://gist.github.com/miku/...
					
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e87094-45b6c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e87094-45b6c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?