Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To establish a connection with an IBM DB2 database using SQLAlchemy in Python, you need to follow these steps:

  1. Install IBM Data Server Driver package: You need to download and install the IBM Data Server Driver package (Db2 driver) on your system, which you can find on the IBM website.

  2. Install ibmdbsa package: Use pip to install the ibmdbsa package, which is a SQLAlchemy adapter for IBM DB2.

    install ibm_db_sa

  3. Create a SQLAlchemy engine: Use the create_engine() function to create a SQLAlchemy engine object that represents a connection to the IBM DB2 database. You need to provide the database URL, username, and password in the connection string.

    from sqlalchemy import create_engine
    
    db_url = "ibm_db_sa://username:password@hostname:port/database_name"
    engine = create_engine(db_url)
    
  4. Test the connection: You can test the connection by using the execute() method of the engine object to execute a simple SQL query.

    result = engine.execute("SELECT COUNT(*) FROM my_table")
    row = result.fetchone()
    print(row[0])
    

Here, "my_table" is the name of the table in the IBM DB2 database that you want to query. The SQL query selects the count of all rows in the table, and the result is printed to the console.