M
M
mikitos592020-12-19 02:39:01
Python
mikitos59, 2020-12-19 02:39:01

How to use a function in other functions?

I have a lot of handlers, where there is a constant connection to the database and checking the cell. I decided to separate the connect function so as not to constantly register a connection to the database. How to make to use this function in all handlers ? Thanks for the answer)

def connect(message: types.Message):
    connect = sqlite3.connect('main.db')
    cursor = connect.cursor()
    cursor.execute('SELECT Bat FROM Users WHERE id = ?', (message.from_user.id))
    result = cursor.fetchone()
    if result is None:
        print('none')
        
        
@dp.message_handler(text='Hi')

    for row in result:
        if row == 'X':
            cursor.execute("SELECT `Glo` FROM `Scev` WHERE `test` = 'test'")
            row = cursor.fetchone()
            await message.answer(row[0], reply_markup=il_1)
    connect.close()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Eremin, 2020-12-19
@Sergei_Erjemin

Use the design ... That's what it's made for... with ... as

O
o5a, 2020-12-19
@o5a

If the goal is to use a single connection, can be done via a class.

class DataBase():
    def __init__(self, database_name):
        self.conn = sqlite3.connect(database_name)
        self.cursor = self.conn.cursor()

    def commit(self):
        self.conn.commit()

    def close(self):
        self.conn.close()

# создаем объект класса
db = DataBase('my_db.db')
cursor = db.cursor

# и в любой функции можем использовать
cursor.execute ...
db.commit()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question