Home > Software design >  Why is the program showing no output?
Why is the program showing no output?

Time:01-20

I ran this query for fetching the details of "tom" which is NOT in the table. So, MySQL as usual returns 'empty set' if I run it in MySQL command client.

import mysql.connector as c
mydb = c.connect(host='localhost', user='root', passwd='mysql')
pointer = mydb.cursor()
pointer.execute('use menagerie')
pointer.execute("select * from pet where name = 'tom'")
for x in pointer:
    print(x)

I ran this code using MySQL python connector but it didn't say 'empty set' like MySQL, just gave the following output:

C:\Users\dhruv\AppData\Local\Programs\Python\Python39\python.exe D:/Programmes/Mysql.py

Process finished with exit code 0

So my question is how do I make the program return a user defined message when MySQL doesn't give any output?

CodePudding user response:

You can check the number of rows returned with pointer.rowcount.

if pointer.rowcount == 0:
    print("empty result")
else:
    for x in pointer:
        print(x)

Reference: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-rowcount.html

CodePudding user response:

Instead of for loop, you can use print(pointer.fetchall()). So it will return empty set [], in case of no result. And try to use try{}...catch{} for handling error/warnings efficiently.

  •  Tags:  
  • Related