Connecting to IBM DB2 database

Connecting to IBM DB2 database

In this article I would like to share the steps to be followed to connect to IBM DB2 database from Jupyter Notebook and read data into a data frame. After few iterations I was able to connect to the database and retrieve the data.

No more of blabbering and let's get to the work!!

Pre-requisites:

Creating an IBM DB2 instance and importing data into it. Created resources can be checked at https://cloud.ibm.com/resources

No alt text provided for this image

Creating new Service-Credentials . These credentials will have the details HOSTNAME, UID,PASSWORD with which we can connect to the database

No alt text provided for this image

Installing ibm-db package for executing SQL statements against DB2 via jupyter notebooks

pip install ibm-db


Establishing connection to database from Jupyter Notebook:

Import the installed packages and other needed packages

import ibm_db
import ibm_db_dbi
import pandas as pd

Connecting to the database server by using ibm_db.connect function and passing on the service-credentials created.

conn = ibm_db.connect("DATABASE=BLUDB;HOSTNAME=YourHostName;PORT=YourPortNumber;PROTOCOL=TCPIP;UID=YourUID;PWD=YOURPWD;","", "")

pconn = ibm_db_dbi.Connection(conn)

#Calling the pconn variable will return something like 

<ibm_db_dbi.Connection at 0x5398008h340>

#confirming a connection has been establised 

After establishing the connection, we can now execute SQL commands and read data into the data frame by using pd_read.sql function

df = pd.read_sql('SQL statement to execute',pconn)

We can use df.head() to check the data and then proceed further with our Analysis.

Hope this helps!


Dear Deepthi Popuri My name is Carlos Mata. I'm trying to connect to db2 database from Python and it's giving below error. What can I be doing wrong? My db2 database is local. Thanks.

  • No alternative text description for this image
Like
Reply

To view or add a comment, sign in

More articles by Deepthi Popuri

Explore content categories