lundi 25 octobre 2021

query database using sqlite3.connect and check for matching results

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?

Aucun commentaire:

Enregistrer un commentaire