IBM DB2 Python Driver
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
- breaking On Windows and Linux, `ibm-db` requires the IBM Data Server Driver for ODBC and CLI to be pre-installed on the system. The `pip install` command only installs the Python bindings. This external driver is typically downloaded from IBM's support portal.
- gotcha After installing the IBM Data Server Driver for ODBC and CLI, you may need to set environment variables such as `IBM_DB_HOME` (pointing to the driver's installation directory) or update `LD_LIBRARY_PATH` (Linux) / `DYLD_LIBRARY_PATH` (macOS) to ensure the Python driver can locate the native libraries.
- gotcha Connection strings for DB2/Informix databases can be complex. Ensure all parameters (DATABASE, HOSTNAME, PORT, PROTOCOL, UID, PWD) are correctly specified. Common issues include incorrect port numbers or hostname resolutions.
- gotcha For ORM integration (e.g., SQLAlchemy), `ibm-db` alone is often not enough. You typically need the `ibm-db-sa` package (SQLAlchemy adapter for ibm-db) in addition to `ibm-db`.
Install
-
pip install ibm-db
Imports
- ibm_db
import ibm_db
Quickstart
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}")