0

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.

1
  • 1
    Check if data is an empty list. Commented Nov 28, 2020 at 5:36

2 Answers 2

1

when there are no records satisfying the given condition (name='Fluff' in your case), mysql returns an empty set and no error is produced.

mysql> select * from job;
+-----+-------------+--------+
| Eno | designation | salary |
+-----+-------------+--------+
|   1 | PGT         |  21000 |
|   3 | TGT         |  19000 |
|   4 | PGT         |  23000 |
|   5 | Primary     |  12000 |
+-----+-------------+--------+
4 rows in set (0.02 sec)

mysql> select * from job where Eno=7;
Empty set (0.00 sec)

Instead of using a try and except block, you could check whether data is an empty list

mycursor.execute("SELECT * FROM pet  where name='Fluff'")
data = mycursor.fetchall()
if bool(data)==False:
      print("Not found")
else:     
      for i in data:
           print(i)
Sign up to request clarification or add additional context in comments.

Comments

1

You've to include the exception you want so, the exception pop-up:

try:
    mycursor.execute("SELECT * FROM pet  where name='Fluff'")
    data = mycursor.fetchall()
    for i in data:
        print(i)

except sql.Error as err:
    print("Error Code: ", err)

3 Comments

Thanks for trying to help. But, here, the except block isn't executing. So, the error code won't be printed.
Can you provide demo from from your data, please? Because i want to check how many items in your tuple output.
There are 9 records. Click this link to download the sample database. downloads.mysql.com/docs/menagerie-db.zip

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.