P
P
PesyCorm2021-03-02 22:45:55
Python
PesyCorm, 2021-03-02 22:45:55

How to avoid repeating code with opening a database (sqlite3, Python)?

Hey! Tell me, how can I take out the logic of opening a db and checking if a table has been created?
For example, there are two functions: one adds a user, the other returns a list of users. And every time I need to check if there is a table, create if not

def add_user_into_db(login, password):

  with sqlite3.connect('users_base.db') as db:
    db_cursor = db.cursor()
    db_cursor.execute("CREATE TABLE IF NOT EXISTS users (login TEXT, password TEXT)")
    db.commit()

    добавить_пользователя()

def select_from_db(sel):

  with sqlite3.connect('users_base.db') as db:
    db_cursor = db.cursor()
    db_cursor.execute("CREATE TABLE IF NOT EXISTS users (login TEXT, password TEXT)")
    db.commit()

    список_пользователей()

How can I avoid repeating the code with opening the database and checking the table?
Thanks for the answer!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alan Gibizov, 2021-03-02
@PesyCorm

PesyCorm , I see it all like this:

The code
import sqlite3


def test_db(db):
    try:
        db_cursor = db.cursor()
        db_cursor.execute("CREATE TABLE IF NOT EXISTS users (login TEXT, password TEXT)")
        db.commit()
        return True
    except DBError:  # тут надо правильную ошибку правильно обрабатывать, я не копался, какую именно и как
        return False


def add_user_into_db(db, login, password):
    if test_db(db):
        добавить_пользователя(login, password)


def select_from_db(db, sel):
    if test_db(db):
        return список_пользователей(sel)


if __name__ == '__main__':
    login = 'my_login'
    password = 'my_password'
    sel = 'string_for_select'
    with sqlite3.connect('users_base.db') as db:
        add_user_into_db(db=db, login=login, password=password)
        print(select_from_db(db=db, sel=sel))

This is also not the best option, in a good way it should be done through pythonway and OOP, i.e. through ORM SQLAlchemy and all that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question