Db2

 View Only

IBM DB2 with Python : Tutorial

By Youssef Sbai Idrissi posted Mon July 24, 2023 01:00 PM

  

Using IBM DB2 with Python can be a powerful way to interact with your relational database and perform data-related tasks. In this tutorial, I'll guide you through the process of connecting to an IBM DB2 database, executing queries, and fetching results using Python.

Before we start, make sure you have the following prerequisites:

  1. IBM DB2 Database: Ensure that you have access to an IBM DB2 database and have the necessary credentials to connect to it.

  2. Python and Required Libraries: Make sure you have Python installed on your system. Additionally, you'll need to install the ibm_db and ibm_db_sa libraries to interact with IBM DB2 from Python. You can install them using pip:

pip install ibm_db ibm_db_sa

Once you have the prerequisites in place, follow these steps:

Step 1: Import Required Libraries

import ibm_db import ibm_db_sa from sqlalchemy import create_engine

Step 2: Establish a Connection

# Replace the placeholders with your actual DB2 database credentials database_username = 'your_db_username' database_password = 'your_db_password' database_hostname = 'your_db_hostname' database_port = 'your_db_port' database_name = 'your_db_name' # Construct the connection string connection_string = ( f"DATABASE={database_name};" f"HOSTNAME={database_hostname};" f"PORT={database_port};" f"PROTOCOL=TCPIP;" f"UID={database_username};" f"PWD={database_password};" ) # Establish the connection try: conn = ibm_db.connect(connection_string, '', '') print("Connection established successfully.") except Exception as e: print(f"Error: {e}")

Step 3: Create an SQLalchemy Engine (Optional) Using SQLalchemy allows you to work with the database in a more convenient way with Python. If you prefer using SQLalchemy, you can create an engine using the connection string and execute queries via the engine.

engine = create_engine(f"db2+ibm_db_sa://{database_username}:{database_password}@{database_hostname}:{database_port}/{database_name}") # Test the engine try: result = engine.execute("SELECT 1 FROM SYSIBM.SYSDUMMY1") print("Engine connected successfully.") except Exception as e: print(f"Error: {e}")

Step 4: Execute Queries and Fetch Results Now that you have established a connection, you can execute SQL queries and fetch results using either ibm_db or the SQLalchemy engine.

Using ibm_db:

# Sample SELECT query query = "SELECT * FROM your_table_name LIMIT 10" # Execute the query stmt = ibm_db.exec_immediate(conn, query) # Fetch the results while ibm_db.fetch_row(stmt): # Get the data for each row col1_value = ibm_db.result(stmt, 0) col2_value = ibm_db.result(stmt, 1) # ... (repeat for other columns as needed) print(col1_value, col2_value)

Using SQLalchemy:

# Sample SELECT query using the engine query = "SELECT * FROM your_table_name LIMIT 10" # Execute the query and fetch results result_set = engine.execute(query) # Fetch the results for row in result_set: # Get the data for each row col1_value = row[0] col2_value = row[1] # ... (repeat for other columns as needed) print(col1_value, col2_value)

Step 5: Close the Connection Don't forget to close the connection when you're done working with the database. 

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

That's it! You now have the basic knowledge to connect to an IBM DB2 database and perform queries using Python. You can build upon this foundation to perform more advanced operations like data insertion, updates, and deletions. Always remember to handle your database credentials securely, especially if you plan to deploy your Python script or application.

0 comments
11 views

Permalink