I want to search a record in a SQL table and if that record is not found, I want to print an error message. I am using a try/except block to do that. But, the error message is not shown. What I think is happening is that when SQL fails to find that record, it won't raise an error. It will just print an empty line. So, the except block is not being executed as python thinks the try block was executed successfully.
Code:
import mysql.connector as sql
mydb = sql.connect(host = "localhost", user = "root", passwd = "password", database = "menagerie")
mycursor = mydb.cursor()
try:
mycursor.execute("SELECT * FROM pet where name='Fluff'")
data = mycursor.fetchall()
for i in data:
print(i)
except:
print("Not found")
Here, in the table pet, there is no record having the name Fluff. So, I want to print the "Not Found" message. But, python prints an empty string.
If there is any way to solve the problem, whether using try/except or any other method, please do let me know. Thanks.
datais an empty list.