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?
CodePudding user response:
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)')