Python and Oracle

Connect to Oracle database with Python

Why is Python important for Oracle DBAs these days?

Traditionally, Bash and Perl are two most languages chosen by Oracle DBAs for scripting in operating systems. However, these days Python has changed the game. Python is flexible and there are many developed libraries available to work with.  All modern Unix and Linux systems come with Python on board; for example, Oracle Linux 6.1 ships with Python 2.6.6. Besides, since Oracle Autonomous came, DBAs’ roles have changed. Thus, learning Python and Oracle database together has more advantages for your future career. Obviously start point is to know, how to connect to Oracle database with Python.

Requirements:

  1. python
  2. cx-Oracle
  3. Oracle instant client


Python

First of all, you have to install Python on the computer which the Python code is going to be run. For download please check on python.org. Please download the latest stable version. At the moment the latest version is 3.8.1

Installing Python is pretty straightforward. Please flow the instruction in the mentioned above web site. Open your command prompt/terminal you have to see your Python version with the commands below:


cx-Oracle

cx_Oracle is a module that enables access to Oracle Database and conforms to the Python database API specification. by clicking on the link, you will find good documentation regards to use cases and examples using cx-Oracle. We’ll install cx-library with the commands below:

If you have difficulties with installation cx-oracle, please check the cx- oracle installation document.

Oracle Instant Client

If your Oracle database is on a remote computer, then download and unzip the client libraries from the free Oracle Instant Client “Basic” or “Basic Light” package for your operating system architecture. Download Instant Client

For Windows users, it’s important to add Instant Client’s location into the Path. Also if you want to use TNS for advantage simplifying connection to the Oracle database, you have to add TNS_ADMIN to the Environment Variable.

At the end of preparation for connecting to Oracle database with Python, it’s worth to know through the below diagram, what exactly will happen between Python and Oracle Database.

Connection logic between Python and Oracle Databases

Connect to Oracle database with Python

before having the first connection, let’s check our database and TNSNAMES.

As you saw, our cluster is up and running. We’ve got a service, its name is nima. We are going to use this service which has been registered on SCAN to connect to the database.

TNS on the client machine:

Finally the Python code:

Output:

I hope this post be useful to you.

Leave a reply:

Your email address will not be published.

Captcha loading...