Home > Blockchain >  Why is it necessary to establish a tnsnames.ora file prior to running a python-oracledb query?
Why is it necessary to establish a tnsnames.ora file prior to running a python-oracledb query?

Time:08-03

When using cx_Oracle (8.3.0), it is simple to connect to an Oracle DB with just this line of code:

con = cx_Oracle.connect(user = myname, password = mypw, dsn = "myDBprod")

When I swap out for oracledb module (1.0.2), I get an error:

con = oracledb.connect(user = myname, password = mypw, dsn = "myDBprod")

DatabaseError: DPY-4026: cannot connect to database. File tnsnames.ora not found in C:\Oracle\InstantAdmin

While researching this, I found this post: With python-oracledb what does 'DPY-4027: no configuration directory to search for tnsnames.ora' mean But I have no clue why all these extra steps are necessary.

CodePudding user response:

I can explain why this is necessary. With cx_Oracle, an Instant Client (or Oracle Database) installation is required. These installations have a default location for tnsnames.ora: <install_dir>/network/admin/tnsnames.ora. So if you put the file in that location you don't need to specify its location. The thin driver doesn't require an Oracle Client (or Database) installation, so there is no default location. So you have to do one of the following:

  • set the environment variable TNS_ADMIN to point to the location where your tnsnames.ora file is found
  • pass the location where your tnsnames.ora file is found in your code, as in:
con = oracledb.connect(user=myname, password=mypw, dsn="myDBprod",
                       config_dir="/the/directory/of/tnsnames.ora")

If you have an Oracle Client installation already (since you were using cx_Oracle), you can also enable thick mode which behaves the same way as cx_Oracle. You can do that by doing this:

oracledb.init_oracle_client()
  • Related