在Python/MySQLdb中检查空查询集

2 投票
1 回答
7228 浏览
提问于 2025-04-17 18:53

我找不到这个问题的简单答案。我正在用Python的MySQLdb库,执行一个查询语句,我想检查返回的结果集是否为空。

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 个回答

3

这很简单,不过你差点走了个更复杂的路。

if get_port.fetchone():
    do_something_here()

你也可以用这个

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

不过那样更长,而且效率更低。

撰写回答