如何在python

时间:2016-11-30 12:55:35

标签: python oracle

我有这样的声明:

try:
   cx_oracle..connect(username/password@hostname:port/service)
except cx_Oracle.DatabaseError:
   #do_stuff

假设我提供了有效的username,空的password,无效的hostname和无效的service名称;我正在except块内编写条件,以便根据Oracle错误代码完成某些操作。

如何在不更正已发生的第一个错误的情况下列出所有可能的数据库错误?

Actual o/p: TNS: listener does not currently know of service requested 
Required o/p:  TNS: listener does not currently know of service requested
               empty password
               Invalid host

2 个答案:

答案 0 :(得分:2)

您可以在元组中添加多个错误。然后,您可以使用e。

访问任何错误
try:
    cx_oracle..connect(username/password@hostname:port/service)
except (cx_Oracle.DatabaseError, Error1, Error2) as e:
    # do stuff

你也可以有多个例外。

try:
    cx_oracle..connect(username/password@hostname:port/service)
except cx_Oracle.DatabaseError:
    # do stuff
except Error1:
    # do stuff

答案 1 :(得分:0)

我不久前遇到过类似的问题,在stackoverflow上发现了这个问题,它会捕获多个错误:

    try:
        cur.execute("insert into project_source_code(project, path) values(:project_id,:prj_path)",(project_id, prj_path))

    except cx_Oracle.DatabaseError as e:
        error, = e.args
        print(error.code)
        print(error.message)
        print(error.context)