【问题标题】:What is the return value of Connection.ping() in cx_oracle?cx_oracle 中 Connection.ping() 的返回值是多少?
【发布时间】:2017-07-28 21:27:01
【问题描述】:

我刚刚安装了一个python包:cx_oracle。从the cx_oracle document我找到了一个方法:Connection.ping(),它被描述为“Ping服务器,可以用来测试连接是否仍然活跃。”。

但是文档没有提到ping()的返回值是什么。

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

#!/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()会在连接正常时返回None,或者在连接关闭后抛出异常:cx_Oracle.InterfaceError: not connected

还有其他可能的返回值吗?为什么不直接返回 True 或 False?

【问题讨论】:

    标签: python oracle cx-oracle


    【解决方案1】:

    cx_Oracle documentation states that 这是:

    此方法是 DB API 定义的扩展,仅在 Oracle 10g R2 及更高版本中可用。

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

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

    当连接不可用时,会引发InterfaceError。采用 is_connected() 方法来检查连接而不引发 错误。

    出现错误时引发 InterfaceError

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

    • 如果连接处于活动状态,则不会返回
    • 如果连接处于非活动状态,则会引发 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;
    }
    

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 如果ping 返回None 连接仍处于活动状态,否则返回类似cx_Oracle.OperationalError: ORA-03135: connection lost contact 的错误
    • @Superdooperhero 如果同时引发异常,它如何返回值?
    • @GeorgeBirbilis 注意else
    • 所以你的意思是有三个结果?活动时无,失败时出现错误(比如超时),关闭时出现异常(手动关闭或从未打开时)?
    • @GeorgeBirbilis 正如@Superdooperhero 所描述的,有两种结果。如果连接处于活动状态,connectionObject.ping() 返回None,因此isOpen 返回True。如果连接不活跃,connectionObject.ping() 会抛出错误。 try/except 捕获抛出的错误,因此isOpen 返回False,这意味着连接已关闭。
    猜你喜欢
    • 1970-01-01
    • 2017-01-06
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多