cx_Oracle在没有tnsnames.ora文件的情况下连接到Oracle Connection Manager

时间:2018-04-11 16:57:11

标签: python cx-oracle

我需要通过OCM连接到Oracle,非OCM连接看起来很简单

conn_str = 'user/password@host:port/service_name'

# oracle connection
self.con = cx_Oracle.connect(conn_str)

使用tnsnames.ora

时可以将其翻译成相同的内容
db_alias = 
       (DESCRIPTION=               
           ) 
           (ADDRESS= 
              (PROTOCOL=TCP)(HOST=DatabaseHost)(PORT=DatabasePort) 
           ) 
           (CONNECT_DATA= 
              (SERVICE_NAME=DatabaseService)
           ) 
       )

当我们使用tnsnames.ora连接到OCM时,会添加以下内容

db_alias = 
   (DESCRIPTION= 
          ***(SOURCE_ROUTE=YES)
          (ADDRESS= 
              (PROTOCOL=TCP) (HOST=ConnectionManagerHost)(PORT=ConnectionManagerPort)***
       ) 
       (ADDRESS= 
          (PROTOCOL=TCP)(HOST=DatabaseHost)(PORT=DatabasePort) 
       ) 
       (CONNECT_DATA= 
          (SERVICE_NAME=DatabaseService)
       ) 
   )

我们如何在python中使用cx_Oracle做同样的事情?

1 个答案:

答案 0 :(得分:0)

在连接字符串中使用TNS别名:

conn_str = 'user/password@db_alias'  # use the entry from the tnsnames.ora file
self.con = cx_Oracle.connect(conn_str)

或使用其他形式的connect()的别名,如下所示:

self.con = cx_Oracle.connect('user', 'password', 'db_alias')