Oracle Database Python Driver

3.4.2 · active · verified Sun Mar 29

oracledb is the official Oracle Database adapter for Python, designed to connect Python applications directly to Oracle Database. It is the successor to the popular cx_Oracle driver, providing a modern, high-performance interface that conforms to the Python Database API v2.0 Specification. It features both a 'Thin' mode, which requires no Oracle Client libraries, and an optional 'Thick' mode for advanced functionalities. The library is actively maintained by Oracle, with frequent releases; the current version is 3.4.2.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to an Oracle Database using `oracledb` in its default Thin mode, execute a simple SQL query, and fetch the result. It uses environment variables for credentials to avoid hardcoding sensitive information.

import os
import oracledb

# Database credentials from environment variables for security
USERNAME = os.environ.get('ORACLE_DB_USER', 'your_username')
PASSWORD = os.environ.get('ORACLE_DB_PASSWORD', 'your_password')
CONNECT_STRING = os.environ.get('ORACLE_DB_DSN', 'localhost/orclpdb') # e.g., 'hostname:port/service_name'

try:
    # Establish a connection in Thin mode (default)
    with oracledb.connect(user=USERNAME, password=PASSWORD, dsn=CONNECT_STRING) as connection:
        print(f"Successfully connected to Oracle Database: {connection.version}")

        with connection.cursor() as cursor:
            # Execute a simple query
            cursor.execute("SELECT SYSDATE FROM DUAL")
            for row in cursor:
                print(f"Current database date: {row[0]}")

except oracledb.Error as e:
    error_obj, = e.args
    print(f"Error connecting to Oracle Database: {error_obj.message}")
    print("Please ensure ORACLE_DB_USER, ORACLE_DB_PASSWORD, and ORACLE_DB_DSN environment variables are set correctly,")
    print("or replace the placeholder values in the script.")

view raw JSON →