检查Python / MySQLdb中的空查询集

时间:2013-03-13 00:07:46

标签: python mysql mysql-python

我似乎找不到这个问题的简单答案。我正在使用MySQLdb for Python,我正在运行一个select语句,我想检查是否返回了一个空查询集。

get_port = db.cursor()
get_port.execute(""" SELECT port FROM nar_ports WHERE port=%s AND hostname=%s;""", (device_port,PE))

我试过了

if not get_port:

这不匹配。所以我试过

for result in get_port.fetchall():
    existing_port = result[0]
if not existing_port:

但它似乎甚至没有进入循环。所以我试着检查长度

if len(get_port) == 0:

但似乎你无法在sql对象上运行len。所以我检查对象是否有无值。

if get_port = None:

但这似乎也不起作用。

我确定有一个简单的解决方案,但我似乎无法找到它。任何帮助将不胜感激。提前谢谢。

欢呼声

1 个答案:

答案 0 :(得分:2)

虽然你差不多走了很长的路,但这很简单。

if get_port.fetchone():
    do_something_here()

您也可以使用

if len(get_port.fetchmany()):
    do_something_here()

但这更长,效率更低。