How to check with python if the table is empty?

Using python and MySQLdb, how can I check if there are any records in mysql table (innodb)?

+3
source share
2 answers

Just select one line. If you get nothing, it is empty! (Example from MySQLdb site)

import MySQLdb
db = MySQLdb.connect(passwd="moonpie", db="thangs")
results = db.query("""SELECT * from mytable limit 1""")
if not results:
    print "This table is empty!"
+7
source

Sort of

import MySQLdb
db = MySQLdb.connect("host", "user", "password", "dbname")
cursor = db.cursor()
sql = """SELECT count(*) as tot FROM simpletable"""
cursor.execute(sql)
data = cursor.fetchone()
db.close()
print data

prints the number or entries in the table simpletable.
Then you can check if it is greater than zero.

+3
source

Source: https://habr.com/ru/post/1736317/


All Articles