Tuesday 28 August 2018

Connecting to oracle sql developer database with python

Wondering how to connect to Oracle SQL developer using python ?

It's a low hanging fruit for you!

Surprising.. This is the way to go...

Prerequisites 

  • SQL Developer 4.1.4
  • HR database
  • Python 3.6.x

Installing Oracle package

Windows platform

c:\pip install cx_Oracle

This would install the oracle package in its default package path.

Python Code

Open editor (Notepad++), copy-paste below code 
--------------------------------------------------------------------------------------------------------------------------
from __future__ import print_function

import cx_Oracle
import time
import sys

# Connect as user "hr" with password "welcome" to the "oraclepdb" service running on this computer(localhost).
#creating a connecting link to the database.

connection = cx_Oracle.connect('hr/welcome@localhost/orclpdb');

#To know the execution time of the query
start = time.time();

#define a cursor object 
cur = connection.cursor();

#Version of the oracle database
print( connection.version);

#simple select statement
cur.execute("SELECT * FROM EMPLOYEES");
row = cur.fetchall();

print(row);

print("\nNumber of row(s) fetched", len(row));

#printing the time taken to execute the query
elapsed = (time.time() - start);
print("\nTotal time taken to execute","{0:.2f}".format(elapsed), "seconds.");

#close the cursor and the connection.
cur.close();
connection.close();

Congrats! you have successfully executed your first oracle connection program.

You can find more information on oracle site:
http://www.oracle.com/technetwork/articles/dsl/python-091105.html