Oracle Database Connection in Python

Hello geek! In this article, we will learn how to set up a connection between the Oracle database and our Python program in a simple way.

First of all, we need to have the Oracle database of versions greater than or equal to 11.x preinstalled in your system.

Python program to set up Oracle Database connection

 

Installing cx_Oracle module

Now, install the cx_Oracle module by typing the following command in cmd.

pip install cx_Oracle

Establishing a connection

We can establish a connection between the Oracle database and our python program with the help of connect( ) method. Here, co is a connection object.

co = cx_Oracle.connect(user = 'database_username', password = 'database_password')

We can also simply write – connect( ‘database_username/database_password’ )

Closing a connection

It is necessary to close the connections as soon as our work is done. We will use close( ) method to close the database connection. We can include this in finally block.

co.close()

Sometimes, we may encounter many exceptions while dealing with databases. For eg. giving a wrong username or password raises DatabaseError exception. So, to handle these exceptions we will include our code in try & except block.

import cx_Oracle

try:
    co=cx_Oracle.connect('Username/Password')
    print("Connected")
    
except Exception as e:
    print("Error: ",str(e))
    
finally:
    if co:
        co.close()

Output:

Connected

Instead of always closing our connection using close( ) method, we can use with statement which simplifies our code.

import cx_Oracle
try:
    with cx_Oracle.connect('Username/Password') as co:
        print("Connected")
        
except Exception as e:
    print("Error: ",str(e))

Output:

Connected

If you get the output as above, Bingo! you have been successfully connected.
Else if you are facing any difficulties, feel free to post them below.

That’s all for now. Hope you found this helpful!

Leave a Reply

Your email address will not be published.