I'm trying to create a script which will check if entry is in connected database, if found it will return entry and if not it will ask if user wants to add it. Script is connecting db without problems, and retrun correct information when entry is found. But when entry is not in db nothing is returned back. I tried two different ways
- Tuple doesn't exist:
def vrn_exist():
vrn = input('Registration Number: ')
vrn = vrn.upper()
#check if vrn is in database
for row in cursor.execute("SELECT * FROM vw_vehicles WHERE regnum= ?", [vrn]):
cursor.fetchone()
if not row:
print("NO")
continue
else:
print("YES")
- len of tuple:
for row in cursor.execute("SELECT * FROM vw_vehicles WHERE regnum= ?", [vrn]):
data=cursor.fetchone()
#print(row)
#return True
#if entry is in database show details
if len(row) != 0:
car_details(row)
#if entry not in database insert new line
elif len(data) == 0:
print('Car not in db. Would you like to add it?')
CodePudding user response:
Since you're using fetchone it will return None if no data is match in your query.
for row in cursor.execute("SELECT * FROM vw_vehicles WHERE regnum= ?", [vrn]):
data=cursor.fetchone()
#if entry is in database show details
if data != None:
car_details(row)
#if entry not in database insert new line
elif data == None:
print('Car not in db. Would you like to add it?')
CodePudding user response:
Rather than using a loop to process one result, ask the database for the first row using fetchone()
. If there's no record, it'll return None
, so you can react accordingly:
data = cursor.execute("SELECT * FROM vw_vehicles WHERE regnum=?;", [vrn]).fetchone()
if data is None:
print("Car not in db. Would you like to add it?")
else:
car_details(data)