F
F
flys_12022-02-16 17:15:07
Python
flys_1, 2022-02-16 17:15:07

How to solve this problem with SQLite?

Gives an error message

"UnboundLocalError: local variable 'singup' referenced before assignment"
.
PS I know that I made a mistake in the word "signup" but that's not the point.

import sqlite3

class Database:
    def __init__(self, db_file):
        self.connection = sqlite3.connect(db_file)
        self.cursor = self.connection.cursor()

    def add_user(self, user_id):
        with self.connection:
            return self.cursor.execute("INSERT INTO 'users' ('user_id') VALUES (?)", (user_id,))

    def user_exists(self, user_id):
        with self.connection:
            result = self.cursor.execute("SELECT * FROM 'users' WHERE 'user_id' = ?", (user_id,)).fetchall()
            return bool(len(result))
    def set_nikname(self, user_id, nickname):
        with self.connection:
            return self.cursor.execute("UPDATE 'users' SET 'nickname' = ? WHERE 'user_id' = ?", (nickname, user_id,))

    def get_singup(self, user_id):
        with self.connection:
            result = self.cursor.execute("SELECT 'singup' FROM 'users' WHERE 'user_id' = ?", (user_id,)).fetchall()
            for row in result:
                singup = str(row[0])
            return singup

    def set_singup(self, user_id, singup):
        with self.connection:
            return self.cursor.execute("UPDATE 'users' SET 'singup' = ? WHERE 'user_id' = ?", (singup, user_id,))

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dr. Bacon, 2022-02-16
@bacon

where do you get this crooked code from? https://qna.habr.com/q/1060608

V
Vindicar, 2022-02-16
@Vindicar

for row in result:
    singup = str(row[0])

Silently implies that result will contain at least one line. This is far from a fact.
If result is empty, then singup will not be assigned a value.

O
o5a, 2022-02-17
@o5a

As already explained, if there is no user, then the data will not be returned, as a result of the cycle there will be no. With a simple change, you can simply return the result inside the loop:

...
            for row in result:
                singup = str(row[0])
                return singup

or directly
...
            for row in result:
                return str(row[0])

In this case, if there is a user, it will return his data. If not, then None. And if special connection parameters were not specified, then row returns as text, so you can simply:
return row[0]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question