Basic Usage of Oracle Database in a Python Application: A Step-by-Step Guide

In this article, we’ll explore the basic usage of Oracle Database in a Python application.

Posted on

Oracle Database is a robust and widely-used relational database management system (RDBMS) known for its scalability and performance. In this article, we’ll explore the basic usage of Oracle Database in a Python application. We’ll cover the steps for connecting to Oracle, performing common database operations, and handling data using the cx_Oracle library.

Prerequisites

Before we start, make sure you have the following prerequisites in place:

  1. Oracle Database: Oracle Database should be installed and running. You can download it from the official Oracle Database Downloads page.

  2. Oracle Client: Install the Oracle Instant Client on your system. This client is required for interacting with the database from Python. You can download it from the Oracle Instant Client Downloads page.

  3. Python: Make sure you have Python installed on your system. You can download Python from the official Python website.

  4. cx_Oracle: Install the cx_Oracle package, which is the official Oracle Database driver for Python. You can install it using pip:

    pip install cx_Oracle
    

Step 1: Connecting to Oracle

To use Oracle Database in a Python application, you first need to establish a connection to the database. Here’s a basic example of how to do this:

import cx_Oracle

# Database configuration
username = 'your_username'
password = 'your_password'
dsn = 'your_dsn'

# Create a connection
try:
    connection = cx_Oracle.connect(username, password, dsn)

    if connection:
        print("Connected to Oracle Database")

    # Perform database operations here

except cx_Oracle.Error as e:
    print(f"Error: {e}")

finally:
    if 'connection' in locals():
        connection.close()
        print("Connection closed")

Replace 'your_username', 'your_password', and 'your_dsn' with your Oracle Database credentials and the Data Source Name (DSN) for your database.

Step 2: Performing Database Operations

Once connected, you can perform various database operations, such as creating tables, inserting data, querying data, updating records, and deleting records. Here are some examples:

Creating a Table

try:
    cursor = connection.cursor()

    create_table_query = """
    CREATE TABLE users (
        id NUMBER(10) PRIMARY KEY,
        username VARCHAR2(50) NOT NULL,
        email VARCHAR2(100) NOT NULL
    )
    """

    cursor.execute(create_table_query)
    print("Table 'users' created successfully")

except cx_Oracle.Error as e:
    print(f"Error: {e}")

finally:
    if 'cursor' in locals():
        cursor.close()

Inserting Data

try:
    cursor = connection.cursor()

    insert_query = "INSERT INTO users (id, username, email) VALUES (:1, :2, :3)"
    data = (1, "john_doe", "[email protected]")

    cursor.execute(insert_query, data)
    connection.commit()
    print("Data inserted successfully")

except cx_Oracle.Error as e:
    print(f"Error: {e}")

finally:
    if 'cursor' in locals():
        cursor.close()

Querying Data

try:
    cursor = connection.cursor()

    select_query = "SELECT * FROM users"

    cursor.execute(select_query)

    for row in cursor:
        print(f"ID: {row[0]}, Username: {row[1]}, Email: {row[2]}")

except cx_Oracle.Error as e:
    print(f"Error: {e}")

finally:
    if 'cursor' in locals():
        cursor.close()

Updating Data

try:
    cursor = connection.cursor()

    update_query = "UPDATE users SET email = :1 WHERE username = :2"
    data = ("[email protected]", "john_doe")

    cursor.execute(update_query, data)
    connection.commit()
    print("Data updated successfully")

except cx_Oracle.Error as e:
    print(f"Error: {e}")

finally:
    if 'cursor' in locals():
        cursor.close()

Deleting Data

try:
    cursor = connection.cursor()

    delete_query = "DELETE FROM users WHERE username = :1"
    data = ("john_doe",)

    cursor.execute(delete_query, data)
    connection.commit()
    print("Data deleted successfully")

except cx_Oracle.Error as e:
    print(f"Error: {e}")

finally:
    if 'cursor' in locals():
        cursor.close()

Step 3: Error Handling

It’s important to handle errors gracefully when working with databases. In the examples above, cx_Oracle provides error handling for many common database errors. You can catch and handle exceptions as needed in your application.

Conclusion

In this article, we’ve covered the basic usage of Oracle Database in a Python application using cx_Oracle. You’ve learned how to connect to an Oracle Database, create tables, insert data, query data, update records, and delete records. Oracle Database is a powerful and scalable RDBMS, and these fundamental skills will serve as a solid foundation for building more complex database-driven applications with Oracle and Python.