How to Call ‘DB2’ from Python

Like other languages, in Python, you can connect to DB2. In this post, I am sharing logic to establish a connection between Python and DB2. Here is How to Categorize Python top Uses.

Like COBOL, JAVA, C++, in Python, you can connect to RDBMS. And, you can execute SQL queries. You need a database connection to work with RDBMS. Once a connection is established, you can run SQL queries.

DB2 from Python

Step-1: Connect to the DB2 local (un-cataloged database.)

import ibm_db
conn = ibm_db.connect("database","username","password")

Step-2: Connect to the DB2 cataloged database.

import ibm_db
                PWD=password;", "", "")

Step-3: SQL Query to Execute.

import ibm_db
conn = ibm_db.connect("database","username","password")
stmt = ibm_db.exec_immediate(conn, 
"UPDATE employee SET bonus = '1000' WHERE job = 'MANAGER'")
print "Number of affected rows: ", ibm_db.num_rows(stmt)

Step-4: Explanation.

  • ibm_db.exec_immediate  => Function to execute SQL query.
  • ibm_db.num_rows => Function to get the result.


Related Posts

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.