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.