cx_oracle 中 Connection.ping() 的 return 值是多少?

What is the return value of Connection.ping() in cx_oracle?

我刚刚安装了一个python包:cx_oracle. From the cx_oracle document我找到了一个方法:Connection.ping(),描述为"Ping the server which can be used to test if the connection is still active.".

但是文档没有提到ping()的return值是多少。

我写了一些代码来做测试:

#!/usr/bin/env python3
import cx_Oracle
conn = cx_Oracle.connect("...")
print(conn.ping()) # display:None
conn.close()
print(conn.ping()) # raise exception: cx_Oracle.InterfaceError: not connected

从测试结果来看,我发现 ping() 会 return None if the connection is OK or raise exception: cx_Oracle.InterfaceError: not connected 连接关闭后。

还有其他可能的 return 值吗?为什么不只是 return 对或错?

cx_Oracle documentation states that这是:

This method is an extension to the DB API definition and is only available in Oracle 10g R2 and higher.

但是,此方法未记录在 PEP 249 中 - 当前 Python 数据库 API 规范在 connection methods or optional extensions(或其他任何与此相关的地方)中。

PEP 249 的 MySQL 实现也 has this method;文档指出:

When the connection is not available, an InterfaceError is raised. Use the is_connected() method to check the connection without raising an error.

Raises InterfaceError on errors.

由于这与 cx_Oracle 行为相同,因此我认为这就是您问题的答案,并且您确定的行为是正确的:

  • 没有return如果连接是活动的
  • 如果连接未激活,则会引发 InterfaceError

如果我们查看 the code for .ping(),它确认这是该方法的实施方式:

static PyObject *Connection_Ping(
    udt_Connection *self,               // connection
    PyObject* args)                     // arguments
{
    sword status;

    if (Connection_IsConnected(self) < 0)
        return NULL;
    status = OCIPing(self->handle, self->environment->errorHandle,
            OCI_DEFAULT);
    if (Environment_CheckForError(self->environment, status,
            "Connection_Ping()") < 0)
        return NULL;
    Py_INCREF(Py_None);
    return Py_None;
}

感谢 Ben 的回答,给定 cx_Oracle 库中的 connectionObject,这至少应该包含您可能想要的内容。

def isOpen(connectionObject):
    try:
        return connectionObject.ping() is None
    except:
        return False