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. Also, read 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: How to Connect DB2 local or un-cataloged database.

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

Step-2: How to connect the DB2 cataloged database.

import ibm_db
ibm_db.connect("DATABASE=name;HOSTNAME=host;
PORT=60000;PROTOCOL=TCPIP;UID=username;
                PWD=password;", "", "")

Step-3: DB2 SQL Query How 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.

References

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.