Answer the question
In order to leave comments, you need to log in
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()
список_пользователей()
Answer the question
In order to leave comments, you need to log in
PesyCorm , I see it all like this:
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))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question