您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

cx_Oracle和异常处理-好的做法?

cx_Oracle和异常处理-好的做法?

但是,如果无法连接,则db不会再存在-这就是我在db = None上面进行设置的原因。但是,这是好习惯吗?

不,设置db = None不是最佳实践。有两种可能性,要么连接到数据库将起作用,要么将它不起作用。

由于引发的异常已被捕获且未重新引发,因此请继续直至到达cursor = db.Cursor()

db == None,因此,TypeError: 'nonetype' object has no attribute 'Cursor'将引发类似的异常。由于已经捕获了数据库连接失败时生成的异常,因此掩盖了失败的原因。

就我个人而言,除非您打算稍后再次尝试,否则我总是会提出连接异常。如何捕捉取决于您自己;如果错误仍然存??在,我将通过电子邮件发送“去检查数据库”的电子邮件

该变量db在您的try:... except块中分配。如果该connect方法有效,则将db其替换为连接对象。

无论哪种方式,db都不会使用的初始值。

但是,我听说将异常处理用于流控制是不好的做法。

与其他语言不同,Python 确实 将异常处理用于流控制。在回答的最后,我已经链接到有关堆栈溢出和程序员的几个问题,这些问题都提出了类似的问题。在每个示例中,您都会看到“ but but in Python”一词。

这并不是说您应该精打细算,但是Python通常使用EAFP的口头禅:“请求宽恕比允许容易。” 我如何检查变量是否存在中投票最多的三个示例很好地说明了如何同时使用和不使用流量控制。

嵌套异常是个好主意吗?还是有更好的方法来处理像这样的依存/级联异常?

嵌套异常没有任何问题,只要您明智地执行它即可。考虑您的代码。您可以删除所有异常并将整个内容包装在一个try:... except块中。如果引发了异常,那么您就知道它是什么,但是要精确地查明出了什么问题要困难一些。

如果您想通过电子邮件发送电子邮件给自己,会发生cursor.execute什么?cursor.execute为了执行这一任务,您应该有一个例外。然后,您重新引发异常,以便将其捕获在外部try:...。不重新引发代码将导致您的代码继续运行,好像什么都没发生,并且您在外部try:...处理异常的任何逻辑都将被忽略。

最终,所有异常都继承自BaseException

另外,有些部分(例如连接失败)我希望脚本终止,因此注释掉了sys.exit()调用

添加一个简单的类以及如何调用它,这大致就是我将要做的事情。如果要在后台运行,那么打印错误是不值得的- 人们不会坐在那里手动寻找错误。无论采用哪种标准方式,都应将其记录下来,并通知适当的人员。由于这个原因,我已经删除了打印内容,并替换为要记录的提醒。

connect方法失败并引发异常时,由于将类拆分为多个函数execute,因此在尝试断开连接后,调用将不会运行且脚本将完成。

import cx_Oracle

class Oracle(object):

    def connect(self, username, password, hostname, port, servicename):
        """ Connect to the database. """

        try:
            self.db = cx_Oracle.connect(username, password
                                , hostname + ':' + port + '/' + servicename)
        except cx_Oracle.DatabaseError as e:
            # Log error as appropriate
            raise

        # If the database connection succeeded create the cursor
        # we-re going to use.
        self.cursor = self.db.cursor()

    def disconnect(self):
        """
        Disconnect from the database. If this fails, for instance
        if the connection instance doesn't exist, ignore the exception.
        """

        try:
            self.cursor.close()
            self.db.close()
        except cx_Oracle.DatabaseError:
            pass

    def execute(self, sql, bindvars=None, commit=False):
        """
        Execute whatever sql statements are passed to the method;
        commit if specified. Do not specify fetchall() in here as
        the sql statement may not be a select.
        bindvars is a dictionary of variables you pass to execute.
        """

        try:
            self.cursor.execute(sql, bindvars)
        except cx_Oracle.DatabaseError as e:
            # Log error as appropriate
            raise

        # Only commit if it-s necessary.
        if commit:
            self.db.commit()

然后调用它:

if __name__ == "__main__":

    oracle = Oracle.connect('username', 'password', 'hostname'
                           , 'port', 'servicename')

    try:
        # No commit as you don-t need to commit DDL.
        oracle.execute('ddl_statements')

    # Ensure that we always disconnect from the database to avoid
    # ORA-00018: Maximum number of sessions exceeded. 
    finally:
        oracle.disconnect()
Oracle 2022/1/1 18:38:48 有355人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶