Connecting to Oracle Database in Python

Summary: In this tutorial, you will learn how to connect to the Oracle Database server using the python-oracledb package.

Creating a new project #

First, open your terminal and create a new project:

mkdir py
cd py
python -m venv .venv
cd .venvCode language: plaintext (plaintext)

Second, activate the virtual environment:

.venv/Scripts/activateCode language: plaintext (plaintext)

Third, install python-oracledb package in the virtual environment using pip:

pip install python-oracledbCode language: Python (python)

Creating a configuration file #

Step 1. Open the project directory in your favorite code editor.

Step 2. Create a new file config.py with the following:

username = 'OT'
password = 'oracle'
dsn = '192.168.2.18/freepdb1'Code language: Python (python)

We specify three parameters:

  • Username is the user account you use to connect to the Oracle Database server.
  • password is the password of the user.
  • dsn is the data source name that specify the Oracle Database Server’s IP address (192.168.2.18) and the pluggable database (freepdb1).

You need to change these parameters to yours to make it works.

Connecting to the Oracle Database #

Step 1. Create a new file within the project directory called connect.py:

import config
import oracledb
import logging


def connect() -> oracledb.Connection:
    try:
        connection = oracledb.connect(
            user=config.username,
            password=config.password,
            dsn=config.dsn
        )
        logging.info("Successfully connected to the Oracle database.")
        return connection
    except oracledb.Error as e:
        logging.error(f"Failed to connect to the database: {e}")
        raiseCode language: Python (python)

How it works:

First, import necessary modules:

import config
import oracledb
import loggingCode language: Python (python)

We imported the config module so we can use the username, password, and dsn for connecting to the Oracle Database server. Additionally, we imported the oracledb module from python-oracledb package and built-in logging Python module for logging out the critical information.

Second, define a connect() function that connects to the Oracle Database Server using the connection parameters specified in the config.py file:

def connect() -> oracledb.Connection:
    try:
        connection = oracledb.connect(
            user=config.username,
            password=config.password,
            dsn=config.dsn
        )
        logging.info("Successfully connected to the Oracle database.")
        return connection
    except oracledb.Error as e:
        logging.error(f"Failed to connect to the database: {e}")
        raise
Code language: Python (python)

The connect() function returns a Connection object from the oracledb module. Inside the function, we call the the connect() function from the oracledb module to connect to the Oracle Database Server.

If an exception occurs, we log and reraise it so the code that calls the function can handle it gracefully.

Step 2. Create main.py file:

import logging
import oracledb
from connect import connect

logging.basicConfig(
    level=logging.INFO, 
    format='%(asctime)s - %(levelname)s - %(message)s'
)

def main():
    try:
        with connect() as connection:
            logging.info(f"Database version: {connection.version}")
    except oracledb.Error as error:
        logging.critical(f"An unhandled database error occurred: {error}")
    except Exception as e:
        logging.critical(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    main()Code language: Python (python)

How it works:

First, import the connect() function from the connect module and the logging and oracledb modules

import logging
import oracledb
from connect import connectCode language: Python (python)

Second, configure a simple logging that shows the time, logging level, and message:

logging.basicConfig(
    level=logging.INFO, 
    format='%(asctime)s - %(levelname)s - %(message)s'
)Code language: Python (python)

Third, define the main() function that calls the connect() function to connect to the Oracle Database Server and handle exceptions:

def main():
    try:
        with connect() as connection:
            logging.info(f"Database version: {connection.version}")
    except oracledb.Error as error:
        logging.critical(f"An unhandled database error occurred: {error}")
    except Exception as e:
        logging.critical(f"An unexpected error occurred: {e}")Code language: Python (python)

If the connection succeeds, we log out the version of the Oracle Database. If exceptions occur, we log the error messages.

Finally, call the main() function:

if __name__ == "__main__":
    main()Code language: Python (python)

Step 3. Run the main.py file:

python main.pyCode language: Python (python)

You’ll see the following output:

2025-05-31 21:41:12,342 - INFO - Successfully connected to the Oracle database.
2025-05-31 21:41:12,342 - INFO - Database version: 23.5.0.24.7Code language: plaintext (plaintext)

The output indicates that you’ve successfully connected to your Oracle database.

We’ll use the connect() function in the next tutorials for connecting to the Oracle Database.

Summary #

  • Call the oracledb.connect() function to connect to the Oracle Database server.
Was this tutorial helpful?