python: connecting to an Oracle database using Ora

2019-08-19 00:47发布

问题:

So I can connect to an Oracle database as such:

import cx_Oracle as ora
dsnStr = ora.makedsn(host="ABC.COM", port="ABC_PORT", sid="ABC")
con = ora.connect(user="ABC_USER", password="ABC_PASSWORD", dsn=dsnStr)
print(con.version)
con.close()

and this works very well, but I would like to connect using the Oracle wallet/tnsnames/database.properties (I'm coming from the Java world). Couldn't find anything so far on how to achieve that. Also, how can I "configure" cx_Oracle in terms of the paths to these Oracle wallet/tnsnames/database.properties respective files.

回答1:

cx_Oracle uses the same techniques to connect to the database as SQLPlus. So you can test with SQLPlus first if you find that easier to do.

In order to do this you will need to create a sqlnet.ora configuration file. This allows you to set such parameters as the location of the wallet file. The environment variable TNS_ADMIN can be used to specify the location of this and other configuration files (like tnsnames.ora) if it isn't found in the default location. See the documentation for more information.



回答2:

I can't help with converting the Java side to the C side needed by cx_Oracle but maybe the following will help show what cx_Oracle needs. I'll use an example based on Oracle Exadata Express, which uses a wallet to connect, see the generic instructions for connecting scripting languages to Exadata Express here.

Your exact config & files may differ. As Anthony indicated, the security setup isn't specific to cx_Oracle. More experienced & helpful security experts may lurk in other forums.

For Exadata Express, a pre-supplied wallet zip file is downloaded. For Oracle Call Interface applications like cx_Oracle we just need these files from the zip: sqlnet.ora, tnsnames.ora, and cwallet.sso. You will need to create/find these (or whater you need) files.

My files are:

sqlnet.ora:

WALLET_LOCATION = (SOURCE = (METHOD = file)
                   (METHOD_DATA = (DIRECTORY="$TNS_ADMIN")))

SSL_SERVER_DN_MATCH=yes

tnsnames.ora:

dbaccess = (description=
          (address=(protocol=tcps)(port=1522)(host=whereever.com))
          (connect_data=(service_name=whereever2.com))   
          (security=(ssl_server_cert_dn="CN=wherever2.com,O=Oracle Corporation,L=Redwood Shores,ST=California,C=US"))  
       )

cwallet.sso: I'll leave this to your imagination...

I put those three files in /Users/cjones/Cloud and set the environment to find them:

$ export TNS_ADMIN=/Users/cjones/Cloud

Now I can connect using the connection name in the tnsnames.ora file:

$ sqlplus -l cj/mypassword@dbaccess

SQL*Plus: Release 12.2.0.1.0 Production on Fri Jul 6 10:20:21 2018

Copyright (c) 1982, 2017, Oracle.  All rights reserved.

Last Successful login time: Tue Jul 03 2018 13:00:06 +10:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production

SQL>

In cx_Oracle your dsn would be dbaccess too.