### Install Supporting Libraries Source: https://github.com/oracle/python-oracledb/blob/main/samples/notebooks/README.md Installs essential Python libraries for data analysis and visualization used in the examples. ```bash python -m pip install numpy matplotlib pyarrow pandas ``` -------------------------------- ### Manual Installation of Instant Client on macOS ARM64 Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Manually install the Instant Client Basic package on macOS ARM64 by downloading the DMG, mounting it, and running the install script. Eject the package after installation. ```shell /Volumes/instantclient-basic-macos.arm64-23.3.0.23.09/install_ic.sh ``` -------------------------------- ### Start Jupyter Notebook (macOS Example) Source: https://github.com/oracle/python-oracledb/blob/main/samples/notebooks/README.md Alternative command to start Jupyter notebook using an absolute path, useful if 'jupyter' is not in the system's PATH. ```bash $HOME/Library/Python/3.9/bin/jupyter notebook ``` -------------------------------- ### Manual Installation of Instant Client on macOS Intel x86-64 Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Manually install the Instant Client Basic package for macOS Intel x86-64 by downloading the DMG, mounting it, and executing the install script. Eject the package afterward. ```shell /Volumes/instantclient-basic-macos.x64-19.16.0.0.0dbru/install_ic.sh ``` -------------------------------- ### Install Oracle Instant Client Basic RPM Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install the Oracle Instant Client 'Basic' or 'Basic Light' RPM using dnf. This command installs the specified version of the basic client package. ```shell sudo dnf install oracle-instantclient-basic-23.9.0.25.07-1.el9.x86_64.rpm ``` -------------------------------- ### Example: Start, Suspend, and Resume Sessionless Transaction Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/txn_management.md This example demonstrates starting a new sessionless transaction, performing operations, suspending it, and then resuming it on a different connection. The inserted data will not be visible after suspension until the transaction is committed on the resumed connection. ```python import oracledb connection1 = oracledb.connect(user="hr", password=userpwd, dsn="localhost/orclpdb") txn_id = b"sessionless_txnid" cursor1 = connection1.cursor() cursor1.execute("create table sessionlessTxnTab (id number, name varchar2(50))") # Start a new sessionless transaction connection1.begin_sessionless_transaction(transaction_id=txn_id, timeout=15) # Execute a database operation cursor1.execute("insert into sessionlessTxnTab values(1, 'row1')") # Insert another row cursor1.execute("insert into sessionlessTxnTab values(2, 'row2')") # Suspend the sessionless transaction connection1.suspend_sessionless_transaction() result = cursor1.execute("select * from sessionlessTxnTab") rows = result.fetchall() print(rows) connection1.close() ``` ```python # Resume the transaction in another connection connection2 = oracledb.connect(user="hr", password=userpwd, dsn="localhost/orclpdb") connection2.resume_sessionless_transaction(transaction_id=txn_id) cursor2 = connection2.cursor() cursor2.execute("insert into sessionlessTxnTab values(3, 'row3')") connection2.commit() result = cursor2.execute("select * from sessionlessTxnTab") rows = result.fetchall() print(rows) ``` -------------------------------- ### Install Sphinx and Read the Docs Theme Source: https://github.com/oracle/python-oracledb/blob/main/doc/README.md Use pip to install the necessary tools for building documentation. Ensure you are using the requirements.txt file for accurate dependency management. ```bash python -m pip install --upgrade -r requirements.txt ``` -------------------------------- ### File Centralized Configuration Provider JSON with Multiple Configurations Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/connection_handling.md Example demonstrating how to define multiple database configurations within a single JSON file by using top-level keys. This allows for switching between different connection setups. ```json { "dev": { "connect_descriptor": "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orclpdb)))", "user": "hr", "password": { "type": "plain", "value": "welcome" } }, "test": { "connect_descriptor": "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=testserver)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=testdb)))", "user": "testuser", "password": { "type": "plain", "value": "testpass" } } } ``` -------------------------------- ### Basic Pipelining Example Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/asyncio.md A complete example demonstrating pipeline creation, adding fetch operations, executing the pipeline, and processing the results. Ensure you have an active asynchronous connection. ```python import asyncio import oracledb async def main(): # Create a pipeline and define the operations pipeline = oracledb.create_pipeline() pipeline.add_fetchone("select temperature from weather") pipeline.add_fetchall("select name from friends where active = true") pipeline.add_fetchmany("select story from news order by popularity", num_rows=5) connection = await oracle.connect_async(user="hr", password=userpwd, dsn="localhost/orclpdb") # Run the operations in the pipeline result_1, result_2, result_3 = await connection.run_pipeline(pipeline) # Print the database responses print("Current temperature:", result_1.rows) print("Active friends:", result_2.rows) print("Top news stories:", result_3.rows) await connection.close() asyncio.run(main()) ``` -------------------------------- ### ConnectParams.parse_connect_string() Output Example Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/connection_handling.md Shows the output of the ConnectParams.parse_connect_string() example, including the hook's invocation and the updated connection parameters. ```text host is None, port is 1234, service name is None In myprotocolhook: protocol=tcp arg=localhost/orclpdb host is localhost, port is 1234, service name is orclpdb ``` -------------------------------- ### Install libaio Package Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install the 'libaio' package, which may be named 'libaio1' or 'libaio1t64' on some distributions. This is a prerequisite for Oracle Instant Client. ```shell sudo dnf install libaio ``` -------------------------------- ### Scripted Installation of Instant Client on macOS ARM64 Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Use this script to automate the download, mounting, and installation of the Instant Client Basic package for macOS ARM64. Ensure you are using the latest available DMG. ```shell cd $HOME/Downloads curl -O https://download.oracle.com/otn_software/mac/instantclient/233023/instantclient-basic-macos.arm64-23.3.0.23.09.dmg hdiutil mount instantclient-basic-macos.arm64-23.3.0.23.09.dmg /Volumes/instantclient-basic-macos.arm64-23.3.0.23.09/install_ic.sh hdiutil unmount /Volumes/instantclient-basic-macos.arm64-23.3.0.23.09 ``` -------------------------------- ### Scripted Installation of Instant Client on macOS Intel x86-64 Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Automate the download, mounting, and installation of the Instant Client Basic package for macOS Intel x86-64 using this script. Always use the latest available DMG. ```shell cd $HOME/Downloads curl -O https://download.oracle.com/otn_software/mac/instantclient/1916000/instantclient-basic-macos.x64-19.16.0.0.0dbru.dmg hdiutil mount instantclient-basic-macos.x64-19.16.0.0.0dbru.dmg /Volumes/instantclient-basic-macos.x64-19.16.0.0.0dbru/install_ic.sh hdiutil unmount /Volumes/instantclient-basic-macos.x64-19.16.0.0.0dbru ``` -------------------------------- ### Start Jupyter Notebook Server Source: https://github.com/oracle/python-oracledb/blob/main/samples/notebooks/README.md Starts the Jupyter notebook server in the 'notebooks' directory after setting connection credentials. ```bash cd notebooks export PYO_SAMPLES_ADMIN_USER=system export PYO_SAMPLES_ADMIN_PASSWORD=oracle export PYO_SAMPLES_CONNECT_STRING=localhost/orclpdb export PYO_SAMPLES_MAIN_USER=pythondemo export PYO_SAMPLES_MAIN_PASSWORD=welcome jupyter notebook ``` -------------------------------- ### Install oracledb with Proxy Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/troubleshooting.md Use this command to install oracledb when a network proxy is required. Replace 'http://proxy.example.com:80' with your actual proxy details. ```shell python -m pip install --proxy=http://proxy.example.com:80 oracledb --upgrade ``` -------------------------------- ### Install OpenTelemetry Modules Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/tracing.md Install the necessary OpenTelemetry packages for tracing database operations. ```bash python -m pip install opentelemetry-sdk opentelemetry-api opentelemetry-instrumentation-dbapi ``` -------------------------------- ### Start Apache HTTP Server Source: https://github.com/oracle/python-oracledb/blob/main/samples/containers/app_dev/README.md Start the Apache HTTP server within the running container. Ensure it is configured for WSGI. ```bash $ apachectl start ``` -------------------------------- ### Install Instant Client 23 on Oracle Linux 8 Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install the Oracle Instant Client release and basic package for version 23 on Oracle Linux 8 using dnf. ```shell sudo dnf install oracle-instantclient-release-26ai-el8 sudo dnf install oracle-instantclient-basic ``` -------------------------------- ### Azure App Configuration Connection String Example Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/connection_handling.md An example of a connection string for the Azure App Configuration provider. This string includes the configuration endpoint and authentication parameters. ```python configazureurl = "config-azure://aznetnamingappconfig.azconfig.io/?key=test/&azure_client_id=123-456&azure_client_secret=MYSECRET&azure_tenant_id=789-123" ``` -------------------------------- ### Install Instant Client 23 on Oracle Linux 10 Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install the Oracle Instant Client release and basic package for version 23 on Oracle Linux 10 using dnf. ```shell sudo dnf install oracle-instantclient-release-26ai-el10 sudo dnf install oracle-instantclient-basic ``` -------------------------------- ### Install Instant Client 23 on Oracle Linux 9 Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install the Oracle Instant Client release and basic package for version 23 on Oracle Linux 9 using dnf. ```shell sudo dnf install oracle-instantclient-release-26ai-el9 sudo dnf install oracle-instantclient-basic ``` -------------------------------- ### Example Output of Fetched BINARY Vector Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/vector_data_type.md This is an example of the output format when fetching data from a BINARY vector column. ```default (array("B", [180, 150, 100])) ``` -------------------------------- ### Install msal Library Source: https://github.com/oracle/python-oracledb/blob/main/samples/deep_data_security/README.md Install the Microsoft Authentication Library (msal) required for Microsoft Entra ID token flows. ```bash python -m pip install msal ``` -------------------------------- ### Install Instant Client 19 on Oracle Linux 8 Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install the Oracle Instant Client release and basic package for version 19 on Oracle Linux 8 using dnf. ```shell sudo dnf install -y oracle-release-el8 sudo dnf install -y oracle-instantclient19.XX-basic ``` -------------------------------- ### Install Instant Client 19 on Oracle Linux 9 Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install the Oracle Instant Client release and basic package for version 19 on Oracle Linux 9 using dnf. ```shell sudo dnf install oracle-instantclient-release-el9 sudo dnf install oracle-instantclient19.XX-basic ``` -------------------------------- ### Start Database Service Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/ha.md Start the newly created database service using DBMS_SERVICE.START_SERVICE. This makes the service available for connections. ```sql BEGIN DBMS_SERVICE.START_SERVICE(''); END; / ``` -------------------------------- ### Install a specific python-oracledb wheel file Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install a pre-built wheel file for a specific architecture and Python version after building packages with GitHub Actions. ```shell python -m pip install oracledb-4.0.0-cp314-cp314-macosx_10_13_universal2.whl ``` -------------------------------- ### Naive Parallel Data Fetching Example Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/sql_execution.md A basic example demonstrating parallel data fetching using multiple threads. Performance benefits depend on various factors and require benchmarking. ```python # A naive example for fetching data in parallel. # Many factors affect whether this is beneficial # The degree of parallelism / number of connections to open NUM_THREADS = 10 # How many rows to fetch in each thread BATCH_SIZE = 1000 # Internal buffer size: Tune for performance oracledb.defaults.arraysize = 1000 # Note OFFSET/FETCH is not particularly efficient. ``` -------------------------------- ### NNE Enabled Example Output Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/troubleshooting.md This is an example of the output from 'SELECT network_service_banner FROM v$session_connect_info;' when Native Network Encryption is enabled. It indicates the specific encryption and checksumming algorithms in use. ```default NETWORK_SERVICE_BANNER ------------------------------------------------------------------------------------- TCP/IP NT Protocol Adapter for Linux: Version 19.0.0.0.0 - Production Encryption service for Linux: Version 19.0.1.0.0 - Production AES256 Encryption service adapter for Linux: Version 19.0.1.0.0 - Production Crypto-checksumming service for Linux: Version 19.0.1.0.0 - Production SHA256 Crypto-checksumming service adapter for Linux: Version 19.0.1.0.0 - Production ``` -------------------------------- ### Install OCI Cloud Native Authentication Modules Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install the Python SDK for Oracle Cloud Infrastructure for the OCI Cloud Native Authentication Plugin using the `[oci_auth]` dependency. ```shell python -m pip install oracledb[oci_auth] ``` -------------------------------- ### File Centralized Configuration Provider JSON Example Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/connection_handling.md Example of a JSON file used by the File Centralized Configuration Provider to store database connection details. Includes basic connection string and optional user credentials. ```json { "connect_descriptor": "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orclpdb)))", "user": "hr", "password": { "type": "plain", "value": "welcome" } } ``` -------------------------------- ### Install Tutorial Database Objects Source: https://github.com/oracle/python-oracledb/blob/main/samples/tutorial/Python-and-Oracle-Database-The-New-Wave-of-Scripting.html Sets up the necessary tables and database objects for the tutorial by running a SQL script. Requires tutorial user credentials. ```python python setup_tutorial.py ``` -------------------------------- ### Insert VECTOR Data using NumPy with Python-oracledb Source: https://github.com/oracle/python-oracledb/blob/main/samples/tutorial/Python-and-Oracle-Database-The-New-Wave-of-Scripting.html Inserts a NumPy array as a VECTOR into the database. This example requires NumPy to be installed and demonstrates the initial setup before type conversion. ```Python import array import numpy import oracledb import db_config con = oracledb.connect( user=db_config.user, password=db_config.pw, dsn=db_config.dsn ) cur = con.cursor() vector_data_64 = numpy.array([11.25, 11.75, 11.5], dtype=numpy.float64) cur.execute( "insert into vtab (id, v64) values (:1, :2)", [202, vector_data_64], ) ``` -------------------------------- ### Start Oracle Database Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/startup.md Requires a privileged connection in PRELIM_AUTH mode to start the database. Subsequent operations like mounting and opening the database must be performed in normal SYSDBA mode. ```python connection = oracledb.connect(mode=oracledb.SYSDBA | oracledb.PRELIM_AUTH) connection.startup() # the following statements must be issued in normal SYSDBA mode connection = oracledb.connect(mode=oracledb.SYSDBA) cursor = connection.cursor() cursor.execute("alter database mount") cursor.execute("alter database open") ``` -------------------------------- ### Install Specific python-oracledb Version Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Use this command to install a particular version of the python-oracledb package, for example, version 3.2.0. ```shell python -m pip install oracledb==3.2.0 ``` -------------------------------- ### Create ParentTable and ChildTable Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/batch_statement.md SQL statements to create the necessary tables for batch operation examples. ```sql create table ParentTable ( ParentId number(9) not null, Description varchar2(60) not null, constraint ParentTable_pk primary key (ParentId) ); create table ChildTable ( ChildId number(9) not null, ParentId number(9) not null, Description varchar2(60) not null, constraint ChildTable_pk primary key (ChildId), constraint ChildTable_fk foreign key (ParentId) references ParentTable ); ``` -------------------------------- ### Example of Using Sessionless Transactions Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/txn_management.md Demonstrates the lifecycle of a sessionless transaction, including starting, suspending, resuming, and committing. ```APIDOC ## Sessionless Transaction Example ### Description This example illustrates how to initiate, suspend, resume, and commit a sessionless transaction across two connections. ### Code Example 1: Starting and Suspending ```python import oracledb connection1 = oracledb.connect(user="hr", password=userpwd, dsn="localhost/orclpdb") txn_id = b"sessionless_txnid" cursor1 = connection1.cursor() cursor1.execute("create table sessionlessTxnTab (id number, name varchar2(50))") # Start a new sessionless transaction connection1.begin_sessionless_transaction(transaction_id=txn_id, timeout=15) # Execute database operations cursor1.execute("insert into sessionlessTxnTab values(1, 'row1')") cursor1.execute("insert into sessionlessTxnTab values(2, 'row2')") # Suspend the sessionless transaction connection1.suspend_sessionless_transaction() result = cursor1.execute("select * from sessionlessTxnTab") rows = result.fetchall() print(rows) connection1.close() ``` ### Code Example 2: Resuming and Committing ```python # Resume the transaction in another connection connection2 = oracledb.connect(user="hr", password=userpwd, dsn="localhost/orclpdb") connection2.resume_sessionless_transaction(transaction_id=txn_id) cursor2 = connection2.cursor() cursor2.execute("insert into sessionlessTxnTab values(3, 'row3')") connection2.commit() result = cursor2.execute("select * from sessionlessTxnTab") rows = result.fetchall() print(rows) ``` ### Expected Output ```default [] [(1, 'row1'), (2, 'row2'), (3, 'row3')] ``` ``` -------------------------------- ### Get Python-oracledb Interface Version Source: https://github.com/oracle/python-oracledb/blob/main/samples/tutorial/Python-and-Oracle-Database-The-New-Wave-of-Scripting.html Retrieves and prints the version of the installed python-oracledb interface. Use double underscores before and after 'version'. ```Python import oracledb import db_config con = oracledb.connect(user=db_config.user, password=db_config.pw, dsn=db_config.dsn) print(oracledb.__version__) # two underscores before and after the version ``` -------------------------------- ### Query Documents Using Query-by-Example Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/soda.md Finds documents in a SODA collection that match a query-by-example pattern. This example searches for documents where the 'name' field starts with 'Ma%'. ```python # Find all documents with names like 'Ma%' print("Names matching 'Ma%'") qbe = {'name': {'$like': 'Ma%'}} for doc in collection.find().filter(qbe).getDocuments(): content = doc.getContent() print(content["name"]) ``` -------------------------------- ### Basic Oracle Database Connection Example Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md A Python script to connect to an Oracle Database using provided credentials and execute a simple query. Ensure you have Python 3.10+ installed. ```python import oracledb import getpass un = "scott" cs = "localhost/orclpdb" # cs = "localhost/freepdb1" # for Oracle AI Database Free users # cs = "localhost/orclpdb1" # some databases may have this service pw = getpass.getpass(f"Enter password for {un}@{cs}: ") with oracledb.connect(user=un, password=pw, dsn=cs) as connection: with connection.cursor() as cursor: sql = "select sysdate from dual" for r in cursor.execute(sql): print(r) ``` -------------------------------- ### Running Oracle Database Free Container Source: https://github.com/oracle/python-oracledb/blob/main/samples/tutorial/Python-and-Oracle-Database-The-New-Wave-of-Scripting.html This command starts a free Oracle Database container. It maps port 1521 and sets the system password. Ensure you have Podman installed. ```bash podman run -p 1521:1521 --name free -e ORACLE_PWD=mysecret \ container-registry.oracle.com/database/free:latest ``` -------------------------------- ### Create Sample Schema Source: https://github.com/oracle/python-oracledb/blob/main/samples/containers/samples_and_db/README.md Initializes the sample schemas within the database. Rerun if it times out, allowing more time for database initialization. ```bash python setup.py ``` -------------------------------- ### Setup Database Connection and Table Source: https://github.com/oracle/python-oracledb/blob/main/samples/notebooks/8-Objects.ipynb Establishes a connection to the Oracle database and creates a table to store SDO_GEOMETRY objects. Includes error handling for table dropping. ```python import os import oracledb un = os.environ.get("PYO_SAMPLES_MAIN_USER", "pythondemo") pw = os.environ.get("PYO_SAMPLES_MAIN_PASSWORD", "welcome") cs = os.environ.get("PYO_SAMPLES_CONNECT_STRING", "localhost/orclpdb") connection = oracledb.connect(user=un, password=pw, dsn=cs) cursor = connection.cursor() try: cursor.execute("drop table TestGeometry") except oracledb.DatabaseError: pass cursor.execute("""create table TestGeometry ( IntCol number(9) not null, Geometry sdo_geometry not null)""") ``` -------------------------------- ### Get Entra ID OAuth2 Token using Curl Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/authentication_methods.md Example of using a curl command with Resource Owner Password Credential (ROPC) Flow to obtain an Entra ID OAuth2 token. The JSON response containing the access token needs to be parsed. ```default curl -X POST -H 'Content-Type: application/x-www-form-urlencoded' \ https://login.microsoftonline.com/your_tenant_id/oauth2/v2.0/token \ -d 'client_id=your_client_id' \ -d 'grant_type=client_credentials' \ -d 'scope=https://oracledevelopment.onmicrosoft.com/your_client_id/.default' \ -d 'client_secret=your_client_secret' ``` -------------------------------- ### Install oracledb with User Permissions Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/troubleshooting.md Use this command to install or upgrade the oracledb package when you lack system-level permissions to modify the Python installation. ```shell python -m pip install oracledb --upgrade --user ``` -------------------------------- ### Build ePub Documentation Locally Source: https://github.com/oracle/python-oracledb/blob/main/doc/README.md To generate ePub documentation, execute the 'epub' target using the Makefile. ```bash make epub ``` -------------------------------- ### Install python-oracledb Driver Source: https://github.com/oracle/python-oracledb/blob/main/samples/notebooks/README.md Installs the python-oracledb driver using pip. ```bash python -m pip install oracledb ``` -------------------------------- ### Setup for Python-oracledb Notebook Source: https://github.com/oracle/python-oracledb/blob/main/samples/notebooks/4-DataFrames.ipynb Establishes a database connection and prepares a table for subsequent operations. Handles potential errors during table dropping. ```python import os import oracledb un = os.environ.get("PYO_SAMPLES_MAIN_USER", "pythondemo") pw = os.environ.get("PYO_SAMPLES_MAIN_PASSWORD", "welcome") cs = os.environ.get("PYO_SAMPLES_CONNECT_STRING", "localhost/orclpdb") connection = oracledb.connect(user=un, password=pw, dsn=cs) cursor = connection.cursor() try: cursor.execute("drop table mytab") except oracledb.DatabaseError: pass cursor.execute("create table mytab (id number, data varchar2(1000))") ``` -------------------------------- ### Install Jupyter Source: https://github.com/oracle/python-oracledb/blob/main/samples/notebooks/README.md Installs the Jupyter notebook environment using pip. ```bash python -m pip install notebook ``` -------------------------------- ### Initialize Oracle Client with Specific Directories Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Use this when you need to specify both the Oracle Instant Client library directory and the configuration directory for files like tnsnames.ora. ```python import oracledb oracledb.init_oracle_client(lib_dir=r"C:\\oracle\\instantclient_23_26", config_dir=r"C:\\oracle\\your_config_dir") ``` -------------------------------- ### Create Database User for Tutorial Source: https://github.com/oracle/python-oracledb/blob/main/samples/tutorial/Python-and-Oracle-Database-The-New-Wave-of-Scripting.html Executes a SQL script to create a new database user for tutorial purposes. Requires SYSTEM or ADMIN privileges. ```python python create_user.py ``` -------------------------------- ### Install python-oracledb Source: https://github.com/oracle/python-oracledb/blob/main/README.md Install the python-oracledb package using pip. This command upgrades to the latest version. ```bash python -m pip install oracledb --upgrade ``` -------------------------------- ### Deploy Sample Flask App With Wallet Source: https://github.com/oracle/python-oracledb/blob/main/samples/containers/app_dev/README.md This command deploys the sample Flask application with a database wallet, suitable for connecting to services like Oracle Autonomous Database Serverless. It requires wallet-related environment variables and volume mounts. ```bash podman run -it -p 8443:8443 --env DEPLOY_SAMPLE_APP="TRUE" \ --env APP_NAME="customer" --env PYO_SAMPLES_MAIN_USER="myuserid" \ --env PYO_SAMPLES_MAIN_PASSWORD="mypassword" \ --env PYO_SAMPLES_CONNECT_STRING="mydb1" \ --env PYO_SAMPLES_WALLET_PASSWORD="mywalletpassword" \ --env TNS_ADMIN=/opt/wallet -v ./sample_app:/opt/app \ -v /disk/path/mywallet:/opt/wallet --name my_app1 \ pyorcldbdev ``` -------------------------------- ### Build Sample Container with Password Source: https://github.com/oracle/python-oracledb/blob/main/samples/containers/samples_and_db/README.md Builds the Docker image for the samples, passing a password for sample schema creation. ```bash podman build -t pyo --build-arg PYO_PASSWORD=a_secret . ``` -------------------------------- ### Example JSON Output Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/json_data_type.md This shows an example of JSON output when using the JSON data type. ```default {mydocument: 'A short CLOB'} ``` -------------------------------- ### Build HTML Documentation Locally Source: https://github.com/oracle/python-oracledb/blob/main/doc/README.md After installing Sphinx and ensuring the 'oracledb' module is importable, use the Makefile to build the HTML documentation. ```bash make ``` -------------------------------- ### Setup Table for Native JSON Source: https://github.com/oracle/python-oracledb/blob/main/samples/notebooks/6-JSON.ipynb Creates a 'customers' table with a native JSON column. Handles potential pre-existence of the table by dropping it first. ```python with connection.cursor() as cursor: try: cursor.execute("drop table customers") except oracledb.DatabaseError: pass cursor.execute("create table customers (k number, json_data json)") ``` -------------------------------- ### Proxy Authentication Setup Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/authentication_methods.md SQL commands to set up proxy authentication by creating proxy and session users and granting the session user permission to connect through the proxy user. ```sql CREATE USER myproxyuser IDENTIFIED BY myproxyuserpw; GRANT CREATE SESSION TO myproxyuser; CREATE USER mysessionuser IDENTIFIED BY itdoesntmatter; GRANT CREATE SESSION TO mysessionuser; ALTER USER mysessionuser GRANT CONNECT THROUGH myproxyuser; ``` -------------------------------- ### Sample Output: Before and After Setting Context Source: https://github.com/oracle/python-oracledb/blob/main/samples/deep_data_security/README.md Compares the database session context and query results before and after applying the end-user identity. Demonstrates the enforcement of Deep Data Security policies. ```text xxxxxxxxxxxxxxxxxxxx Before setting the context xxxxxxxxxxxxxxxxxxxx xs$session username is None (None,) ORA_END_USER_CONTEXT username is None (None,) ORA_END_USER_CONTEXT user token iss = None -- Read contexts through DB query Current user sys_context('userenv', 'current_user') = DB_USR XS session user xs_sys_context('xs$session', 'username') = None -- Sample DB query on table hr.employees ORA-00942: table or view does not exist Help: https://docs.oracle.com/error-help/db/ora-00942/ press enter to set the context xxxxxxxxxxxxxxxxxxxx After setting the context xxxxxxxxxxxxxxxxxxxx xs$session username is sks1@example.onmicrosoft.com ORA_END_USER_CONTEXT username is sks1@example.onmicrosoft.com ORA_END_USER_CONTEXT user token iss = https://sts.windows.net/xxxxxxxx/ -- Read contexts through DB query Current user sys_context('userenv', 'current_user') = XS$NULL XS session user xs_sys_context('xs$session', 'username') = sks1@example.onmicrosoft.com -- Sample DB query on table hr.employees Count of records in hr.employees = 1 Dept ID: 60, First Name: Suraj, SSN: 000-00-0101 ``` -------------------------------- ### Install Test Packages for Python-oracledb Source: https://github.com/oracle/python-oracledb/blob/main/tests/README.md Installs the oracledb library with testing dependencies. Ensure you are using pip to upgrade packages. ```bash python -m pip install --upgrade oracledb[test] ``` -------------------------------- ### Install AWS Configuration Providers Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install the Boto3 package for AWS S3 and Secrets Manager integration using the `[aws_config]` dependency. ```shell python -m pip install oracledb[aws_config] ``` -------------------------------- ### Asyncio Connection Pool Example Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/asyncio.md Demonstrates creating an asynchronous connection pool and executing concurrent queries using asyncio.gather. Ensure the session_callback is defined if needed. ```python import asyncio import oracledb # Assume SQL, userpwd, CONCURRENCY, and init_session are defined elsewhere # SQL = "SELECT SYSDATE FROM DUAL" # userpwd = "your_password" # CONCURRENCY = 5 # async def init_session(connection): # await connection.callproc("dbms_session.set_identifier", ["my_async_app"]) async def query(pool): async with pool.acquire() as connection: await connection.callproc("dbms_session.sleep", [1]) res = await connection.fetchone(SQL) print(res[0].strftime("%H:%M:%S.%f"), '- query with SID-SERIAL#', res[1]) async def main(): pool = oracledb.create_pool_async(user="hr", password=userpwd, dsn="localhost/orclpdb", min=1, max=CONCURRENCY, session_callback=init_session) coroutines = [ query(pool) for i in range(CONCURRENCY) ] await asyncio.gather(*coroutines) await pool.close() asyncio.run(main()) ``` -------------------------------- ### Install python-oracledb for System Python Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Use this command to install the package into the system's Python environment, potentially requiring elevated privileges. ```shell /usr/bin/python3 -m pip install oracledb --upgrade --user ``` -------------------------------- ### Example: Using End-User Security Context Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/connection_handling.md Demonstrates the complete lifecycle of setting, using, and clearing an end-user security context payload on a standalone connection. Includes context creation and database operations. ```python import oracledb import sys def get_token(filename): with open(filename, 'r', encoding='utf-8') as file: token = file.read().strip() return token # Read user and database tokens from files passed as command-line arguments user_token = get_token(sys.argv[1]) db_token = get_token(sys.argv[2]) # Define the name of the data roles data_roles = ["HCM_ROLE"] # Define the context attributes attrs = { "p1": 33, "p2": "test2" } ctx_attrs = { "HR.HCM": attrs } # Create an end-user security context payload context = oracledb.create_end_user_security_context( end_user_identity = user_token, database_access_token = db_token, data_roles = data_roles, attributes = ctx_attrs ) # Create a standalone connection connection = oracledb.connect(user="db_user", password=userpwd, dsn="orclpdb", config_dir="/opt/oracle/config", wallet_location="location_of_pem_file", wallet_password=walletpw) # Set the end-user security context payload on a connection connection.set_end_user_security_context(context) # Execute a database operation within the end user security context with connection.cursor() as cursor: cursor.execute("select 1 from dual") row = cursor.fetchone() print(row) # Clear the end-user security context payload # Subsequent database operations run without the end user security context connection.clear_end_user_security_context() # Execute a database operation without the end user security context with connection.cursor() as cursor: cursor.execute("select 2 from dual") row = cursor.fetchone() print(row) # Close the connection connection.close() ``` -------------------------------- ### Start DRCP Pool in SQL Source: https://github.com/oracle/python-oracledb/blob/main/samples/notebooks/1-Connection.ipynb SQL command to start the Database Resident Connection Pool. This must be executed on the database before the pool can be used. ```sql execute dbms_connection_pool.start_pool() ``` -------------------------------- ### Install python-oracledb without Dependencies Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install python-oracledb without its default dependencies, which is necessary if the cryptography package is unavailable. This forces the package to only work in Thick mode. ```python python -m pip install oracledb --no-deps ``` -------------------------------- ### Create RAW Payload Queue (Classic) Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/aq.md Creates a queue table for RAW payloads and then a classic queue named DEMO_RAW_QUEUE. The queue must be started before use. ```sql begin dbms_aqadm.create_queue_table('MY_QUEUE_TABLE', 'RAW'); dbms_aqadm.create_queue('DEMO_RAW_QUEUE', 'MY_QUEUE_TABLE'); dbms_aqadm.start_queue('DEMO_RAW_QUEUE'); end; / ``` -------------------------------- ### Start a Sessionless Transaction Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/txn_management.md Use `Connection.begin_sessionless_transaction()` to start a new sessionless transaction. You can specify a transaction ID, timeout for suspension, and whether to defer the round-trip to the database. ```python txn_id = b"new_sessionless_txn" connection.begin_sessionless_transaction(transaction_id=txn_id, timeout=120, defer_round_trip=False) ``` -------------------------------- ### Install Built python-oracledb Wheel Package Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/installation.md Install the python-oracledb wheel package that was built from source. The file path should point to the generated .whl file in the 'dist' directory. ```shell python -m pip install dist/oracledb-4.0.0-cp314-cp314-macosx_14_0_arm64.whl ``` -------------------------------- ### Create Connection Pool with Pooled Server (Easy Connect) Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/connection_handling.md Example of creating a connection pool using Easy Connect syntax with a 'pooled' DSN, specifying user credentials and pool parameters. ```python cs = "dbhost.example.com/orclpdb:pooled" pool = oracledb.create_pool(user="hr", password=userpwd, dsn=cs, min=2, max=5, increment=1, cclass="MYAPP") ``` -------------------------------- ### Basic Oracle Database Connection and Query Source: https://github.com/oracle/python-oracledb/blob/main/README.md Connect to an Oracle Database using provided credentials and execute a simple SQL query to fetch the current system date. This example uses a context manager for connection and cursor management. ```python import oracledb import getpass un = "scott" # Sample database username cs = "localhost/orclpdb" # Sample database connection string # cs = "localhost/freepdb1" # For Oracle Database Free users # cs = "localhost/orclpdb1" # Some databases may have this service pw = getpass.getpass(f"Enter password for {un}@{cs}: ") with oracledb.connect(user=un, password=pw, dsn=cs) as connection: with connection.cursor() as cursor: sql = "select sysdate from dual" for r in cursor.execute(sql): print(r) ``` -------------------------------- ### Create and Use Async Connection Pool Source: https://github.com/oracle/python-oracledb/blob/main/doc/src/user_guide/asyncio.md Demonstrates creating an asynchronous connection pool and acquiring/releasing connections using an async context manager. Ensure the pool is closed when no longer needed. ```python import asyncio import oracledb async def main(): pool = oracle.create_pool_async(user="hr", password=userpwd, dsn="localhost/orclpdb", min=1, max=4, increment=1) async with pool.acquire() as connection: with connection.cursor() as cursor: await cursor.execute("select user from dual") async for result in cursor: print(result) await pool.close() asyncio.run(main()) ```