SQLAlchemy Dialect for IBM Data Servers (ibm-db-sa)

0.4.4 · active · verified Thu Apr 16

ibm-db-sa is a SQLAlchemy dialect that enables Python applications to connect to IBM Db2 for LUW, Db2 on Cloud, and Informix data servers. It provides an interface for SQLAlchemy's ORM and core features, leveraging the `ibm_db` DBAPI driver for database communication. The current version is 0.4.4, with releases typically following updates in its core dependencies, `ibm_db` and `SQLAlchemy`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to an IBM Db2 or Informix database using `ibm-db-sa` with SQLAlchemy. It retrieves connection parameters from environment variables for security and flexibility. The example executes a simple query to fetch the current timestamp, printing the result or any connection error.

import os
from sqlalchemy import create_engine, text

# Get credentials from environment variables
# Ensure these are set in your environment or replace with actual values
DB2_USER = os.environ.get('DB2_USER', 'db2inst1')
DB2_PASSWORD = os.environ.get('DB2_PASSWORD', 'password')
DB2_HOST = os.environ.get('DB2_HOST', 'localhost')
DB2_PORT = os.environ.get('DB2_PORT', '50000')
DB2_DATABASE = os.environ.get('DB2_DATABASE', 'SAMPLE')
INFORMIX_SERVER = os.environ.get('INFORMIX_SERVER', '') # Optional for Informix

# Construct the connection string
connection_string = f"ibm_db_sa://{DB2_USER}:{DB2_PASSWORD}@{DB2_HOST}:{DB2_PORT}/{DB2_DATABASE}"
if INFORMIX_SERVER:
    connection_string += f"?INFORMIXSERVER={INFORMIX_SERVER}"

print(f"Attempting to connect to: {connection_string.split('@')[-1].split('?')[0]}")

try:
    engine = create_engine(connection_string)
    with engine.connect() as connection:
        # Example query for Db2. For Informix, adjust query (e.g., SELECT FIRST 1 current FROM systables)
        result = connection.execute(text("SELECT CURRENT_TIMESTAMP AS current_time FROM SYSIBM.SYSDUMMY1"))
        for row in result:
            print(f"Successfully connected! Current Db2 timestamp: {row.current_time}")
except Exception as e:
    print(f"Error connecting or executing query: {e}")
    print("Please ensure your Db2/Informix server is running, credentials are correct, and necessary client drivers are installed.")

view raw JSON →