IBM DB2 Python Driver

3.2.8 · active · verified Fri Apr 10

ibm_db is a Python DBI driver that provides an interface for accessing IBM DB2 (LUW, zOS, iSeries, Cloud Pak for Data) and Informix databases. It implements a subset of the Python DB API 2.0 specification. As of version 3.2.8, it supports Python 3.6 and above and is actively maintained with several releases per year.

Warnings

Install

Imports

Quickstart

Connects to an IBM DB2 database using environment variables for credentials and executes a simple query to fetch table information.

import ibm_db
import os

# Connection details (replace with your actual DB2/Informix details)
# For security, use environment variables in production.
database = os.environ.get('IBM_DB_DATABASE', 'SAMPLE')
hostname = os.environ.get('IBM_DB_HOSTNAME', 'localhost')
port = os.environ.get('IBM_DB_PORT', '50000')
protocol = os.environ.get('IBM_DB_PROTOCOL', 'TCPIP')
uid = os.environ.get('IBM_DB_UID', 'db2inst1')
pwd = os.environ.get('IBM_DB_PWD', 'password')

conn_string = f"DATABASE={database};HOSTNAME={hostname};PORT={port};PROTOCOL={protocol};UID={uid};PWD={pwd};"

try:
    # Connect to the database
    # Note: User/password can be passed separately or embedded in conn_string.
    # Empty strings for user/pwd are allowed if already in conn_string.
    conn = ibm_db.connect(conn_string, "", "")
    print("Connection to DB2 successful!")

    # Execute a query
    stmt = ibm_db.exec_immediate(conn, "SELECT * FROM SYSCAT.TABLES FETCH FIRST 5 ROWS ONLY")

    # Fetch results
    result = ibm_db.fetch_both(stmt)
    while result:
        print(result)
        result = ibm_db.fetch_both(stmt)

    # Close the connection
    ibm_db.close(conn)
    print("Connection closed.")

except Exception as e:
    print(f"Connection or query failed: {e}")

view raw JSON →