Shounak Das
Shounak Das

Reputation: 565

How to execute the except block if try prints an empty string

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.

Upvotes: 0

Views: 310

Answers (2)

Ahmed
Ahmed

Reputation: 924

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)

Upvotes: 1

a121
a121

Reputation: 786

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)

Upvotes: 1

Related Questions