MEHMET BALIOGLU

How To Fix “cx_oracle Database Error ORA-12547: TNS: Lost Contact”

ORA-12547: TNS: Lost Contact Oracle Autonomous Database Python

cx_Oracle is a Python extension module that provides access to Oracle Database from your Python application. You can connect your Python application to an Oracle Database. However, I’ve recently encountered ORA-12547: TNS: lost contact error while connecting to Oracle Autonomous Database.

In this post, I’m going to show you how to fix ORA-12547: TNS: lost contact error while connecting to Oracle Autonomous Database. I’ve encountered this error while trying to connect my Python application to an Oracle Autonomous Database.

import cx_Oracle

# Connecting to DB
dsn = cx_Oracle.makedsn("YOUR-HOST-NAME", 1522, service_name="YOUR-SERVICE-NAME")
connection = cx_Oracle.connect(user="YOUR-USERNAME", password="YOUR-PASSWORD", dsn=dsn, encoding="UTF-8")
# Open Cursor
cursor = connection.cursor()

The above code threw an ORA-12547: TNS: lost contact error. It appeared that this was related to a failure to access to tnsnames.ora file. There was a problem with the TNS_ADMIN environment variable. We can fix this later, as a temporary solution, we are going to point our cx_Oracle to a directory containing our TNSNAMES.ORA file. This is a temporary assignment and we are overriding the TNS_ADMIN environment variable.

So, what we are going to do is to point the cx_Oracle to the directory, or folder, which contains the tnsnames.ora file. In order to do this we are going to import os library and locate the folder:

import cx_Oracle
import os
# Pointing to the tnsnames.ora file
os.environ['TNS_ADMIN'] = 'THE FOLDER WHICH CONTAINS THE TNSNAMES.ORA FILE'
# Connecting to DB
connection = cx_Oracle.connect("YOUR-USERNAME", "YOUR-PASSWORD", "YOUR-SERVICE-NAME")

Don’t forget all the quotation marks and etc.

Problem solved! It can be a real nightmare to deal with Oracle errors and I hope this helps you.