cx_Oracle

8.3.0 · deprecated · verified Thu Apr 09

cx_Oracle is a Python extension module that enables access to Oracle Database, conforming to the Python Database API v2.0 specification. The current version is 8.3.0, released in November 2021, and introduced official support for Python 3.10. However, it is officially deprecated in favor of `python-oracledb` by Oracle, which is recommended for new projects.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to an Oracle database, execute a simple query, and fetch results using `cx_Oracle`. It includes `cx_Oracle.init_oracle_client()` for explicit Oracle Client library path configuration and uses environment variables for sensitive connection details.

import cx_Oracle
import os

# Set the path to the Oracle Instant Client libraries
# This is recommended for programmatically setting the library path since cx_Oracle 8.0
# On Windows, example: r"C:\oracle\instantclient_19_11"
# On Linux/macOS, example: r"/opt/oracle/instantclient_19_11"
# Replace with your actual Instant Client directory or set ORACLE_CLIENT_LIB_DIR env var
oracle_client_lib_dir = os.environ.get('ORACLE_CLIENT_LIB_DIR', '')
if oracle_client_lib_dir:
    try:
        cx_Oracle.init_oracle_client(lib_dir=oracle_client_lib_dir)
        print(f"Initialized Oracle Client from: {oracle_client_lib_dir}")
    except cx_Oracle.Error as e:
        print(f"Warning: Could not initialize Oracle Client from {oracle_client_lib_dir}. Error: {e}")
        print("Ensure Oracle Client libraries are correctly installed and path is valid.")

# Connection details (use environment variables for security in production)
username = os.environ.get('ORACLE_DB_USER', 'hr')
password = os.environ.get('ORACLE_DB_PASSWORD', 'welcome')
# Example DSN: "hostname:port/servicename" or "localhost:1521/XEPDB1"
dsn = os.environ.get('ORACLE_DB_DSN', 'localhost:1521/XEPDB1') 

try:
    # Establish a connection to the Oracle Database
    connection = cx_Oracle.connect(username, password, dsn)
    print("Successfully connected to Oracle Database.")

    # Create a cursor object
    cursor = connection.cursor()

    # Execute a simple SQL query
    cursor.execute("SELECT SYSDATE FROM DUAL")

    # Fetch and print the results
    for row in cursor:
        print(f"Current Oracle DB Date: {row[0]}")

    # Close the cursor and connection
    cursor.close()
    connection.close()
    print("Connection closed.")

except cx_Oracle.Error as e:
    error_obj, = e.args
    print(f"Oracle Database Error: Code {error_obj.code} - {error_obj.message}")
    print("Please check your connection details and Oracle Client setup.")

view raw JSON →