Python and Oracle Introduction

Oracle is a database that can be used in conjunction with Python to create desktop, web and console based application. It can be used to store data, as well as configuration information. Python, together with SQL, can be used to query the data stored within an Orcle database, as well as insert, update and delete the data.

Connecting to an Oracle Database

In order to access data within an Oracle database using Python, a connection to the database must first be established. Below is an example of how this can be achieved. In order for this to work, the third-party module cx_Oracle must be installed.

import cx_Oracle

# Database connection variable.
connect = None

# Database connection arguments.
host = 'localhost'
username = 'DemoUN'
password = 'DemoPW'

try:

    # Connect to database.
    connect = cx_Oracle.connect(username + '/' + password + '@' + host)

    # Message confirming successful database connection.
    print("Database connection successful.")

except cx_Oracle.DatabaseError as e:

    # Confirm unsuccessful connection and stop program execution.
    print("Database connection unsuccessful.")
    quit()

In this example, a ‘try-except’ block is used to catch any exceptions that may arise in connecting to the database. A ‘try-except’ block can be used to handle any exceptions in a user friendly manner. The ‘quit’ statement, after the confirmation of an unsuccessful database connection, stops execution of the program completely, so no further statements are executed.

It should be noted that it isn’t necessary to have the host and database information in separate variables before using them in the database connection. It much depends on personal preference and whether the variables are going to be re-used elsewhere in the program. The database connection variable can be re-written as follows.

# Connect to database.
connect = cx_Oracle.connect('DemoUN/DemoPW@localhost')