首页 > 解决方案 > Python 与 Oracle 数据库

问题描述

我在使用 Python-3 和 cx-oracle 的 Oracle-12c 上。

如何处理以下 SQL 的“No rows returned”查询?如果没有返回行,我希望将字符串“Inactive”分配给结果。

cursor.execute("select STATUS from DOMAINTABLE")
for result in cursor:
    print(result[0])
    row = result.fetchone()
    if row == None:
        break
        print ("Inactive")

标签: pythoncx-oracle

解决方案


您应该遍历光标或调用该fetchone方法,但不能同时执行以下操作:

cursor.execute("select STATUS from DOMAINTABLE")
for status, in cursor:
    print(status)
    break
else:
    print('Inactive')

或者:

cursor.execute("select STATUS from DOMAINTABLE")
row = result.fetchone()
if row is None:
    print('Inactive')
else:
    print(row[0])

推荐阅读