Python interface to Oracle Database implementing DB API 2.0 with Oracle-specific extensions
npx @tessl/cli install tessl/pypi-cx-oracle@8.3.0A mature Python extension module providing comprehensive access to Oracle Database. cx_Oracle implements the Python Database API 2.0 specification with extensive Oracle-specific extensions, enabling Python applications to connect to and interact with Oracle databases (versions 11.2 through 21c) with high performance and advanced Oracle features.
pip install cx_Oracleimport cx_OracleFor aliasing (common pattern):
import cx_Oracle as oracledbimport cx_Oracle
# Create connection
connection = cx_Oracle.connect("username", "password", "hostname:port/servicename")
# Alternative DSN format
dsn = cx_Oracle.makedsn("hostname", 1521, service_name="servicename")
connection = cx_Oracle.connect("username", "password", dsn)
# Execute query
cursor = connection.cursor()
cursor.execute("SELECT employee_id, first_name, last_name FROM employees WHERE department_id = :dept_id", {"dept_id": 10})
# Fetch results
for row in cursor:
print(f"ID: {row[0]}, Name: {row[1]} {row[2]}")
# Execute DML operations
cursor.execute("INSERT INTO employees (employee_id, first_name, last_name) VALUES (:1, :2, :3)", (1001, "John", "Doe"))
connection.commit()
# Close resources
cursor.close()
connection.close()cx_Oracle is built around the Database API 2.0 specification with Oracle-specific enhancements:
Core connection management including direct connections, connection strings, authentication modes, and connection properties for Oracle Database access.
def connect(user=None, password=None, dsn=None, **kwargs) -> Connection: ...
def makedsn(host, port, sid=None, service_name=None, region=None,
sharding_key=None, super_sharding_key=None, **kwargs) -> str: ...
def clientversion() -> tuple: ...
def init_oracle_client(lib_dir=None, config_dir=None, error_url=None,
driver_name=None) -> None: ...
def DateFromTicks(ticks: float) -> Date: ...
def TimestampFromTicks(ticks: float) -> Timestamp: ...
def Time(hour: int, minute: int, second: int): ... # Raises NotSupportedError
def TimeFromTicks(ticks: float): ... # Raises NotSupportedErrorSQL statement execution, parameter binding, result fetching, and cursor management with support for all Oracle SQL features and PL/SQL operations.
class Cursor:
def execute(self, sql: str, parameters=None) -> Cursor: ...
def executemany(self, sql: str, seq_of_parameters) -> None: ...
def fetchone(self) -> tuple: ...
def fetchmany(self, numRows=None) -> list: ...
def fetchall(self) -> list: ...
def callfunc(self, name: str, returnType, parameters=None): ...
def callproc(self, name: str, parameters=None) -> list: ...Connection pooling for scalable applications with configurable pool sizes, connection sharing, and automatic connection management.
class SessionPool:
def __init__(self, user: str, password: str, dsn: str, min: int, max: int, increment: int, **kwargs): ...
def acquire(self) -> Connection: ...
def release(self, connection: Connection) -> None: ...
def close(self, force=False) -> None: ...Handling of CLOB, BLOB, NCLOB, and BFILE objects with streaming read/write operations, temporary LOB creation, and file-based LOB operations.
class LOB:
def read(self, offset=1, amount=None) -> Union[str, bytes]: ...
def write(self, data: Union[str, bytes], offset=1) -> int: ...
def size(self) -> int: ...
def trim(self, newSize=0) -> None: ...
def getvalue(self) -> Union[str, bytes]: ...Document-oriented database operations for JSON documents with collection management, document operations, and query capabilities.
class SodaDatabase:
def createCollection(self, name: str, metadata=None) -> SodaCollection: ...
def openCollection(self, name: str) -> SodaCollection: ...
def getCollectionNames(self, startName=None, limit=None) -> list: ...
class SodaCollection:
def insertOne(self, doc) -> SodaDoc: ...
def find(self) -> SodaOperation: ...
def createIndex(self, spec: dict) -> None: ...SODA (Simple Oracle Document Access)
Oracle Advanced Queueing for message-oriented middleware with message enqueueing, dequeueing, and queue management operations.
class Queue:
def enqOne(self, msgProperties: MessageProperties) -> None: ...
def deqOne(self) -> MessageProperties: ...
def enqMany(self, msgPropertiesList: list) -> None: ...
def deqMany(self, maxMessages: int) -> list: ...Support for Oracle user-defined types including object types, collections (VARRAYs and nested tables), and object attribute access.
class Object:
def copy(self) -> Object: ...
def aslist(self) -> list: ...
def asdict(self) -> dict: ...
def append(self, value) -> None: ...
def extend(self, sequence) -> None: ...
class ObjectType:
def newobject(self) -> Object: ...
@property
def attributes(self) -> list: ...Continuous Query Notification (CQN) and Database Change Notification for real-time monitoring of database changes.
class Subscription:
def __init__(self, connection: Connection, callback, **kwargs): ...
@property
def callback(self): ...
@property
def operations(self): ...cx_Oracle provides a comprehensive exception hierarchy based on the Database API 2.0 specification:
class Error(Exception): ...
class Warning(Exception): ...
# Database API standard exceptions
class InterfaceError(Error): ...
class DatabaseError(Error): ...
class DataError(DatabaseError): ...
class OperationalError(DatabaseError): ...
class IntegrityError(DatabaseError): ...
class InternalError(DatabaseError): ...
class ProgrammingError(DatabaseError): ...
class NotSupportedError(DatabaseError): ...All exceptions provide detailed error information including Oracle error codes and messages.
cx_Oracle fully implements the Python Database API 2.0 specification:
:param_name)# Module metadata
__version__: str # Module version string
version: str # Module version string (alias)
buildtime: str # Build timestamp
apilevel: str # DB API level ("2.0")
threadsafety: int # Thread safety level (2)
paramstyle: str # Parameter style ("named")Oracle database types are available as module constants:
# API types (DB API 2.0)
STRING: ApiType
BINARY: ApiType
NUMBER: ApiType
DATETIME: ApiType
ROWID: ApiType
# Oracle-specific database types (preferred names)
DB_TYPE_BFILE: DbType
DB_TYPE_BINARY_DOUBLE: DbType
DB_TYPE_BINARY_FLOAT: DbType
DB_TYPE_BINARY_INTEGER: DbType
DB_TYPE_BLOB: DbType
DB_TYPE_BOOLEAN: DbType
DB_TYPE_CHAR: DbType
DB_TYPE_CLOB: DbType
DB_TYPE_CURSOR: DbType
DB_TYPE_DATE: DbType
DB_TYPE_INTERVAL_DS: DbType
DB_TYPE_INTERVAL_YM: DbType
DB_TYPE_JSON: DbType
DB_TYPE_LONG: DbType
DB_TYPE_LONG_RAW: DbType
DB_TYPE_NCHAR: DbType
DB_TYPE_NCLOB: DbType
DB_TYPE_NUMBER: DbType
DB_TYPE_NVARCHAR: DbType
DB_TYPE_OBJECT: DbType
DB_TYPE_RAW: DbType
DB_TYPE_ROWID: DbType
DB_TYPE_TIMESTAMP: DbType
DB_TYPE_TIMESTAMP_LTZ: DbType
DB_TYPE_TIMESTAMP_TZ: DbType
DB_TYPE_VARCHAR: DbType
# Deprecated synonyms (for compatibility)
BFILE: DbType # Use DB_TYPE_BFILE
BLOB: DbType # Use DB_TYPE_BLOB
CLOB: DbType # Use DB_TYPE_CLOB
CURSOR: DbType # Use DB_TYPE_CURSOR
FIXED_CHAR: DbType # Use DB_TYPE_CHAR
NCHAR: DbType # Use DB_TYPE_NCHAR
NCLOB: DbType # Use DB_TYPE_NCLOB
TIMESTAMP: DbType # Use DB_TYPE_TIMESTAMP# Authentication modes
DEFAULT_AUTH: int # Default authentication
SYSDBA: int # SYSDBA administrative privilege
SYSOPER: int # SYSOPER administrative privilege
SYSASM: int # SYSASM administrative privilege
SYSBKP: int # SYSBKP administrative privilege
SYSDGD: int # SYSDGD administrative privilege
SYSKMT: int # SYSKMT administrative privilege
SYSRAC: int # SYSRAC administrative privilege
PRELIM_AUTH: int # Preliminary authentication for startup/shutdown
# Session pool modes
SPOOL_ATTRVAL_WAIT: int # Wait for connection
SPOOL_ATTRVAL_NOWAIT: int # Don't wait for connection
SPOOL_ATTRVAL_FORCEGET: int # Force get connection
SPOOL_ATTRVAL_TIMEDWAIT: int # Timed wait for connection
# Purity levels
ATTR_PURITY_DEFAULT: int # Default purity
ATTR_PURITY_NEW: int # New connection purity
ATTR_PURITY_SELF: int # Self purity
# Database shutdown modes
DBSHUTDOWN_ABORT: int # Abort shutdown
DBSHUTDOWN_FINAL: int # Final shutdown
DBSHUTDOWN_IMMEDIATE: int # Immediate shutdown
DBSHUTDOWN_TRANSACTIONAL: int # Transactional shutdown
DBSHUTDOWN_TRANSACTIONAL_LOCAL: int # Local transactional shutdown# Subscription protocols
SUBSCR_PROTO_OCI: int # OCI protocol
SUBSCR_PROTO_MAIL: int # Mail protocol
SUBSCR_PROTO_SERVER: int # Server protocol
SUBSCR_PROTO_HTTP: int # HTTP protocol
# Quality of service flags
SUBSCR_QOS_RELIABLE: int # Reliable messaging
SUBSCR_QOS_DEREG_NFY: int # Deregistration notification
SUBSCR_QOS_ROWIDS: int # Include ROWIDs
SUBSCR_QOS_QUERY: int # Query-level notification
SUBSCR_QOS_BEST_EFFORT: int # Best effort delivery
SUBSCR_QOS_PURGE_ON_NTFN: int # Purge on notification
# Event types
EVENT_NONE: int # No event
EVENT_STARTUP: int # Database startup
EVENT_SHUTDOWN: int # Database shutdown
EVENT_SHUTDOWN_ANY: int # Any shutdown
EVENT_DROP_DB: int # Database drop
EVENT_DEREG: int # Deregistration
EVENT_OBJCHANGE: int # Object change
EVENT_QUERYCHANGE: int # Query change
# Operation codes
OPCODE_ALLOPS: int # All operations
OPCODE_ALLROWS: int # All rows
OPCODE_INSERT: int # Insert operation
OPCODE_UPDATE: int # Update operation
OPCODE_DELETE: int # Delete operation
OPCODE_ALTER: int # Alter operation
OPCODE_DROP: int # Drop operation
OPCODE_UNKNOWN: int # Unknown operation# Dequeue options
DEQ_BROWSE: int # Browse mode
DEQ_LOCKED: int # Locked mode
DEQ_REMOVE: int # Remove mode
DEQ_REMOVE_NODATA: int # Remove without data
# Enqueue/Dequeue navigation
DEQ_FIRST_MSG: int # First message
DEQ_NEXT_MSG: int # Next message
DEQ_NEXT_TRANSACTION: int # Next transaction
# Message delivery modes
MSG_PERSISTENT: int # Persistent message
MSG_BUFFERED: int # Buffered message
MSG_PERSISTENT_OR_BUFFERED: int # Either mode
# Message states
MSG_WAITING: int # Waiting state
MSG_READY: int # Ready state
MSG_PROCESSED: int # Processed state
MSG_EXPIRED: int # Expired stateSee individual capability documents for complete constant definitions and usage examples.