Skip to content

Instantly share code, notes, and snippets.

@tolmachina
Created November 11, 2020 17:53
Show Gist options
  • Save tolmachina/0fb516f1ec949e3d839d92113e6e5dfc to your computer and use it in GitHub Desktop.
Save tolmachina/0fb516f1ec949e3d839d92113e6e5dfc to your computer and use it in GitHub Desktop.

Revisions

  1. tolmachina created this gist Nov 11, 2020.
    335 changes: 335 additions & 0 deletions DB0201EN-Week3-1-1-Connecting-v4-py.ipynb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,335 @@
    {
    "cells": [
    {
    "cell_type": "markdown",
    "metadata": {},
    "source": [
    "<center>\n",
    " <img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/Logos/organization_logo/organization_logo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\" />\n",
    "</center>\n",
    "\n",
    "# Connect to Db2 database on Cloud using Python\n",
    "\n",
    "Estaimted time needed: **15** minutes\n",
    "\n",
    "## Objectives\n",
    "\n",
    "After complting this lab you will be able to:\n",
    "\n",
    "- Import the ibm_db Python library\n",
    "- Enter the database connection credentials\n",
    "- Create the database connection\n",
    "- Close the database connection\n"
    ]
    },
    {
    "cell_type": "markdown",
    "metadata": {},
    "source": [
    "**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.\n",
    "\n",
    "## Import the `ibm_db` Python library\n",
    "\n",
    "The `ibm_db` [API ](https://pypi.python.org/pypi/ibm_db?cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-DB0201EN-SkillsNetwork-20127838&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ&cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-DB0201EN-SkillsNetwork-20127838&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ&cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-DB0201EN-SkillsNetwork-20127838&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ&cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-DB0201EN-SkillsNetwork-20127838&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ) 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.\n",
    "\n",
    "We first import the ibm_db library into our Python Application\n",
    "\n",
    "Execute the following cell by clicking within it and then \n",
    "press `Shift` and `Enter` keys simultaneously\n"
    ]
    },
    {
    "cell_type": "code",
    "execution_count": 1,
    "metadata": {},
    "outputs": [],
    "source": [
    "import ibm_db"
    ]
    },
    {
    "cell_type": "markdown",
    "metadata": {},
    "source": [
    "When the command above completes, the `ibm_db` library is loaded in your notebook. \n",
    "\n",
    "## Identify the database connection credentials\n",
    "\n",
    "Connecting to dashDB or DB2 database requires the following information:\n",
    "\n",
    "- Driver Name\n",
    "- Database name \n",
    "- Host DNS name or IP address \n",
    "- Host port\n",
    "- Connection protocol\n",
    "- User ID (or username)\n",
    "- User Password\n",
    "\n",
    "**Notice:** To obtain credentials please refer to the instructions given in the first Lab of this course\n",
    "\n",
    "Now enter your database credentials below and execute the cell with `Shift` + `Enter`\n"
    ]
    },
    {
    "cell_type": "code",
    "execution_count": 3,
    "metadata": {},
    "outputs": [],
    "source": [
    "#Replace the placeholder values with your actual Db2 hostname, username, and password:\n",
    "dsn_hostname = \"dashdb-txn-sbox-yp-lon02-06.services.eu-gb.bluemix.net\" # e.g.: \"dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net\"\n",
    "dsn_uid = \"zsl80828\" # e.g. \"abc12345\"\n",
    "dsn_pwd = \"x36l7@g9k19g7140\" # e.g. \"7dBZ3wWt9XN6$o0J\"\n",
    "\n",
    "dsn_driver = \"{IBM DB2 ODBC DRIVER}\"\n",
    "dsn_database = \"BLUDB\" # e.g. \"BLUDB\"\n",
    "dsn_port = \"50000\" # e.g. \"50000\" \n",
    "dsn_protocol = \"TCPIP\" # i.e. \"TCPIP\""
    ]
    },
    {
    "cell_type": "code",
    "execution_count": null,
    "metadata": {},
    "outputs": [],
    "source": [
    "{\n",
    " \"db\": \"BLUDB\",\n",
    " \"dsn\": \"DATABASE=BLUDB;HOSTNAME=dashdb-txn-sbox-yp-lon02-06.services.eu-gb.bluemix.net;PORT=50000;PROTOCOL=TCPIP;UID=zsl80828;PWD=x36l7@g9k19g7140;\",\n",
    " \"host\": \"dashdb-txn-sbox-yp-lon02-06.services.eu-gb.bluemix.net\",\n",
    " \"hostname\": \"dashdb-txn-sbox-yp-lon02-06.services.eu-gb.bluemix.net\",\n",
    " \"https_url\": \"https://dashdb-txn-sbox-yp-lon02-06.services.eu-gb.bluemix.net:8443\",\n",
    " \"jdbcurl\": \"jdbc:db2://dashdb-txn-sbox-yp-lon02-06.services.eu-gb.bluemix.net:50000/BLUDB\",\n",
    " \"parameters\": {\n",
    " \"role_crn\": \"crn:v1:bluemix:public:iam::::serviceRole:Manager\"\n",
    " },\n",
    " \"password\": \"x36l7@g9k19g7140\",\n",
    " \"port\": 50000,\n",
    " \"ssldsn\": \"DATABASE=BLUDB;HOSTNAME=dashdb-txn-sbox-yp-lon02-06.services.eu-gb.bluemix.net;PORT=50001;PROTOCOL=TCPIP;UID=zsl80828;PWD=x36l7@g9k19g7140;Security=SSL;\",\n",
    " \"ssljdbcurl\": \"jdbc:db2://dashdb-txn-sbox-yp-lon02-06.services.eu-gb.bluemix.net:50001/BLUDB:sslConnection=true;\",\n",
    " \"uri\": \"db2://zsl80828:x36l7%40g9k19g7140@dashdb-txn-sbox-yp-lon02-06.services.eu-gb.bluemix.net:50000/BLUDB\",\n",
    " \"username\": \"zsl80828\"\n",
    "}"
    ]
    },
    {
    "cell_type": "markdown",
    "metadata": {},
    "source": [
    "## Create the DB2 database connection\n",
    "\n",
    "Ibm_db API uses the IBM Data Server Driver for ODBC and CLI APIs to connect to IBM DB2 and Informix.\n",
    "\n",
    "Lets build the dsn connection string using the credentials you entered above\n"
    ]
    },
    {
    "cell_type": "code",
    "execution_count": 4,
    "metadata": {},
    "outputs": [
    {
    "name": "stdout",
    "output_type": "stream",
    "text": [
    "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=BLUDB;HOSTNAME=dashdb-txn-sbox-yp-lon02-06.services.eu-gb.bluemix.net;PORT=50000;PROTOCOL=TCPIP;UID=zsl80828;PWD=x36l7@g9k19g7140;\n"
    ]
    }
    ],
    "source": [
    "#DO NOT MODIFY THIS CELL. Just RUN it with Shift + Enter\n",
    "#Create the dsn connection string\n",
    "dsn = (\n",
    " \"DRIVER={0};\"\n",
    " \"DATABASE={1};\"\n",
    " \"HOSTNAME={2};\"\n",
    " \"PORT={3};\"\n",
    " \"PROTOCOL={4};\"\n",
    " \"UID={5};\"\n",
    " \"PWD={6};\").format(dsn_driver, dsn_database, dsn_hostname, dsn_port, dsn_protocol, dsn_uid, dsn_pwd)\n",
    "\n",
    "#print the connection string to check correct values are specified\n",
    "print(dsn)"
    ]
    },
    {
    "cell_type": "markdown",
    "metadata": {},
    "source": [
    "Now establish the connection to the database\n"
    ]
    },
    {
    "cell_type": "code",
    "execution_count": 5,
    "metadata": {},
    "outputs": [
    {
    "name": "stdout",
    "output_type": "stream",
    "text": [
    "Connected to database: BLUDB as user: zsl80828 on host: dashdb-txn-sbox-yp-lon02-06.services.eu-gb.bluemix.net\n"
    ]
    }
    ],
    "source": [
    "#DO NOT MODIFY THIS CELL. Just RUN it with Shift + Enter\n",
    "#Create database connection\n",
    "\n",
    "try:\n",
    " conn = ibm_db.connect(dsn, \"\", \"\")\n",
    " print (\"Connected to database: \", dsn_database, \"as user: \", dsn_uid, \"on host: \", dsn_hostname)\n",
    "\n",
    "except:\n",
    " print (\"Unable to connect: \", ibm_db.conn_errormsg() )\n"
    ]
    },
    {
    "cell_type": "markdown",
    "metadata": {},
    "source": [
    "Congratulations if you were able to connect successfuly. Otherwise check the error and try again.\n"
    ]
    },
    {
    "cell_type": "code",
    "execution_count": 6,
    "metadata": {},
    "outputs": [
    {
    "name": "stdout",
    "output_type": "stream",
    "text": [
    "DBMS_NAME: DB2/LINUXX8664\n",
    "DBMS_VER: 11.01.0404\n",
    "DB_NAME: BLUDB\n"
    ]
    }
    ],
    "source": [
    "#Retrieve Metadata for the Database Server\n",
    "server = ibm_db.server_info(conn)\n",
    "\n",
    "print (\"DBMS_NAME: \", server.DBMS_NAME)\n",
    "print (\"DBMS_VER: \", server.DBMS_VER)\n",
    "print (\"DB_NAME: \", server.DB_NAME)"
    ]
    },
    {
    "cell_type": "code",
    "execution_count": 7,
    "metadata": {},
    "outputs": [
    {
    "name": "stdout",
    "output_type": "stream",
    "text": [
    "DRIVER_NAME: libdb2.a\n",
    "DRIVER_VER: 11.05.0400\n",
    "DATA_SOURCE_NAME: BLUDB\n",
    "DRIVER_ODBC_VER: 03.51\n",
    "ODBC_VER: 03.01.0000\n",
    "ODBC_SQL_CONFORMANCE: EXTENDED\n",
    "APPL_CODEPAGE: 1208\n",
    "CONN_CODEPAGE: 1208\n"
    ]
    }
    ],
    "source": [
    "#Retrieve Metadata for the Database Client / Driver\n",
    "client = ibm_db.client_info(conn)\n",
    "\n",
    "print (\"DRIVER_NAME: \", client.DRIVER_NAME) \n",
    "print (\"DRIVER_VER: \", client.DRIVER_VER)\n",
    "print (\"DATA_SOURCE_NAME: \", client.DATA_SOURCE_NAME)\n",
    "print (\"DRIVER_ODBC_VER: \", client.DRIVER_ODBC_VER)\n",
    "print (\"ODBC_VER: \", client.ODBC_VER)\n",
    "print (\"ODBC_SQL_CONFORMANCE: \", client.ODBC_SQL_CONFORMANCE)\n",
    "print (\"APPL_CODEPAGE: \", client.APPL_CODEPAGE)\n",
    "print (\"CONN_CODEPAGE: \", client.CONN_CODEPAGE)"
    ]
    },
    {
    "cell_type": "markdown",
    "metadata": {},
    "source": [
    "## Close the Connection\n",
    "\n",
    "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.\n"
    ]
    },
    {
    "cell_type": "code",
    "execution_count": 8,
    "metadata": {},
    "outputs": [
    {
    "data": {
    "text/plain": [
    "True"
    ]
    },
    "execution_count": 8,
    "metadata": {},
    "output_type": "execute_result"
    }
    ],
    "source": [
    "ibm_db.close(conn)"
    ]
    },
    {
    "cell_type": "markdown",
    "metadata": {},
    "source": [
    "## Summary\n",
    "\n",
    "In this tutorial you established a connection to a DB2 database on Cloud database from a Python notebook using ibm_db API. \n"
    ]
    },
    {
    "cell_type": "markdown",
    "metadata": {},
    "source": [
    "## Author\n",
    "\n",
    "<a href=\"https://www.linkedin.com/in/ravahuja\">Rav Ahuja</a>\n",
    "\n",
    "## Change Log\n",
    "\n",
    "| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n",
    "| ----------------- | ------- | ---------- | ---------------------------------- |\n",
    "| 2020-08-28 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n",
    "\n",
    "<hr>\n",
    "\n",
    "## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n"
    ]
    }
    ],
    "metadata": {
    "kernelspec": {
    "display_name": "Python",
    "language": "python",
    "name": "conda-env-python-py"
    },
    "language_info": {
    "codemirror_mode": {
    "name": "ipython",
    "version": 3
    },
    "file_extension": ".py",
    "mimetype": "text/x-python",
    "name": "python",
    "nbconvert_exporter": "python",
    "pygments_lexer": "ipython3",
    "version": "3.6.11"
    },
    "widgets": {
    "state": {},
    "version": "1.1.2"
    }
    },
    "nbformat": 4,
    "nbformat_minor": 4
    }