query database using sqlite3.connect and check for matching results

Question:

My Discord bot queries a database and checks if there is a matching entry. To check for a matching entry I am using an if statement like here. But somehow my code is not working as expected:

def check_db_entry():

    message = 'Some Message.'
    user_id : int = 1234

    # check if user already exists in database
    # connect to database
    con = get_connection() 
    cur = con.cursor() 

    # search in database
    cur.execute('SELECT id FROM user WHERE id=?', user_id)
    result = cur.fetchone()

    if result:
        print(f'nUser found in db with {user_id}.n')
    else:
        print(f'nNo user found in db with {user_id}.n Create user')

    con.commit()
    con.close()

None of my 2 print statements get printed actually. Which is strange because, the if or else statement should work.

The connection to my database was successful. I already tested this many times just with print(str(result)) Here my code for database setup:

def create_database():

    if not os.path.exists('db'):
        os.mkdir('db')

    # database setup
    try:
        con = sqlite3.connect(SQLITE_DB_PATH)
        cur = con.cursor()
        cur.execute('CREATE TABLE IF NOT EXISTS user (id INTEGER NOT_NULL, balance REAL NOT_NULL, text1 TEXT NOT_NULL, text2 TEXT NOT_NULL)')
        con.commit()
        con.close()
    except Error as e:
        print('Failed to setup database.n' + e)
        exit(1)


# connect to the database, returns connection object
def get_connection():

    try:
        con = sqlite3.connect(SQLITE_DB_PATH)
        return con
    except:
        print('Unable to connect to database. Please try again later.n')
        exit(1)

Am I missing something here?

Asked By: CodeIsLaw

||

Answers:

fetchone() returns None, which is not the same as false, if the query did not return any rows and this is what you should check.

So change to this:

if result is None:
    print(f'nNo user found in db with {user_id}.n Create user')
else:
    print(f'nUser found in db with {user_id}.n') 

Also, you should pass the parameter user_id as a tuple:

cur.execute('SELECT id FROM user WHERE id=?', (user_id,))

Also, NOT_NULL means nothing for SQLite, although it does not throw an error.
You should use NOT NULL:

cur.execute('DROP TABLE IF EXISTS user;') # execute once to drop he table that you created
cur.execute('CREATE TABLE IF NOT EXISTS user (id INTEGER NOT NULL, balance REAL NOT NULL, text1 TEXT NOT NULL, text2 TEXT NOT NULL)') 
Answered By: forpas

def search_habit():

sqliteconn = None

try:

    sqliteconn = sqlite3.connect('dbname.sqlite3')

    # print("Connected to Database Successfully.")
    dbconn = sqliteconn.cursor()
    
    habit_id = input("Enter Habit Id to search: ")
    habit_id = int(habit_id)

    command = """SELECT HabitId,HabitName,Description,Period,Born,Start_Date,Due_Date,Streak,Max_Streak,Max_Days,
                                Break,HabitStatus FROM habits_tracker WHERE HabitId = :hbt_id"""
    dbconn.execute(command, {'hbt_id': habit_id})
    records = dbconn.fetchall()
    lenrecords = len(records)

    if lenrecords > 0:

        for row in records:
            print(row)

    else:
        print("nCurrently, There Is No Record Available.....")

    sqliteconn.commit()
    sqliteconn.close()

except sqlite3.Error as e:
    print("Failure: ", e)

except Exception as ex:
    print("Failure: ", ex)

finally:
    if sqliteconn:
        sqliteconn.close()
Answered By: Muhammad Ali