Ask Your Question
1

How can SQLAlchemy be used to establish a connection with an IBM DB2 database?

asked 2022-05-11 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-12-17 13:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-11 11:00:00 +0000

Seen: 17 times

Last updated: Dec 17 '22