Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/main/06. Databases and SQL for Data Science with Python/04. Accessing Databases using Python/01. Connect to a DB2 Database using Python.ipynb
Views: 4598
Connect to Db2 database on Cloud using Python
Objectives
After completing this lab you will be able to:
Import the ibm_db Python library
Enter the database connection credentials
Create the database connection
Close the database connection
Note: Please follow the instructions given in the first Lab of this course to Create a database service instance of Db2 on Cloud and retrieve your database Service Credentials.
Import the ibm_db
Python library
The ibm_db
API provides a variety of useful Python functions for accessing and manipulating data in an IBM® data server database, including functions for connecting to a database, preparing and issuing SQL statements, fetching rows from result sets, calling stored procedures, committing and rolling back transactions, handling errors, and retrieving metadata.
We first import the ibm_db library into our Python Application
Execute the following cell by clicking within it and then press Shift
and Enter
keys simultaneously
When the command above completes, the ibm_db
library is loaded in your notebook.
Identify the database connection credentials
Connecting to dashDB or DB2 database requires the following information:
Driver Name
Database name
Host DNS name or IP address
Host port
Connection protocol
User ID (or username)
User Password
Notice: To obtain credentials please refer to the instructions given in the first Lab of this course
Now enter your database credentials below and execute the cell with Shift
+ Enter
Create the DB2 database connection
Ibm_db API uses the IBM Data Server Driver for ODBC and CLI APIs to connect to IBM DB2 and Informix.
Build the dsn connection string using the credentials entered above
Now establish the connection to the database
Close the Connection
We free all resources by closing the connection. Remember that it is always important to close connections so that we can avoid unused connections taking up resources.