E
E
enabl32021-09-07 14:26:49
Python
enabl3, 2021-09-07 14:26:49

How to get SQL query data?

Hello.
Please tell me what am I doing wrong? There is a requests.sql
file , I write all requests in it, it contains a request to get all user IDs, it looks like this:

def users_in_db(message):
    conn = sqlite3.connect(db)
    cursor = conn.cursor()
    sql_users_in_db = """SELECT chat_id FROM users;"""
    cursor.execute(sql_users_in_db)
    users = cursor.fetchall()
    print(users)
    conn.close()

now in the commands, file handlers.py , I want to check if there is a user who wrote a message in the database
@dp.message_handler(commands=["users"])
async def process_start_command(message: Message):
    if str(message.chat.id) in str(users_in_db(message)):
        print("зареган")
    else:
        print("не зареган")

the answer comes to the console - the list of IDs of users + is not registered. If I write print(str(users_in_db(message))) in the code and run it, then in the console there will be a list of IDs in the database + None.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
ScriptKiddo, 2021-09-07
@enabl3

Your function doesn't return anything, that's why it always prints "not registered".
If the function does not have a return, then the result of its execution will be None
As a result, if expands into str(message.chat.id) in 'None', which is always False, unless message.chat.id != 'None' or any slice lines.
Use the with context manager so you don't have to close the cursor or the database connection manually.
Return the result from the function so that there is something to work with after it is executed.
Read any Python tutorial. For example, Lutz. This will eliminate a lot of such questions and will greatly help in learning the language.

def users_in_db(message):
    with sqlite3.connect(db) as conn:
        with conn.cursor() as cursor:
            sql_users_in_db = """SELECT chat_id FROM users WHERE chat_id = ?;"""
            cursor.execute(sql_users_in_db, message.chat.id)
            users = cursor.fetchall()
            print(users)
            if users:
                return True
    return False


@dp.message_handler(commands=["users"])
async def process_start_command(message: Message):
    if users_in_db(message):
        print("зареган")
    else:
        print("не зареган")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question