开发者

How to check with python if a table is empty?

Using python and MySQLdb, how can I check if t开发者_运维知识库here are any records in a mysql table (innodb)?


Just select a single row. If you get nothing back, it's empty! (Example from the 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!"


Something like

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

will print the number or records in the simpletable table.
You can then test if to see if it is bigger than zero.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜