我似乎无法找到这个问题的简单答案。我正在使用 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:
但这似乎也不起作用。
我确信有一个简单的解决方案,但我似乎找不到它。任何帮助将不胜感激。提前致谢。
干杯
最佳答案
这很简单,尽管你几乎走了更长的路。
if get_port.fetchone():
do_something_here()
您也可以使用
if len(get_port.fetchmany()):
do_something_here()
但这会花费更长的时间且效率较低。
关于python - 检查 Python/MySQLdb 中的空查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15374654/