11/10/2019

How to connect and fetch result in DB2 through python?

Till now I have automated db2 tasks using shell script, now I'm using python as automation tool.

To use db2 in python, we must install ibm_db2 plugin in python.


apt install python-pip
pip install ibm_db

Then we need to import ibm_db function in our python script.

Now I'll show you a simple script to connect and fetch result using Python script.


import ibm_db

conn = ibm_db.connect("sample","db2inst1","db2inst1")
stmt = ibm_db.exec_immediate(conn, "select * from db2inst1.employee")
print("number of rows: ",ibm_db.fetch_both(stmt))
 Save this commands in file_name.py

 Result:

db2inst1@vinay-Lenovo-Ideapad-Z510:~$ python connect_db2.py
('number of rows: ', {0: u'000010', 1: u'CHRISTINE', 2: u'I', 3: u'HAAS', 4: u'A00', 5: u'3978', 6: datetime.date(1995, 1, 1), 7: u'PRES    ', 8: 18, 'LASTNAME': u'HAAS', 10: datetime.date(1963, 8, 24), 11: '152750.00', 12: '1000.00', 13: '4220.00', 'BIRTHDATE': datetime.date(1963, 8, 24), 'SALARY': '152750.00', 'MIDINIT': u'I', 'BONUS': '1000.00', 'FIRSTNME': u'CHRISTINE', 'SEX': u'F', 'JOB': u'PRES    ', 9: u'F', 'PHONENO': u'3978', 'WORKDEPT': u'A00', 'EDLEVEL': 18, 'EMPNO': u'000010', 'COMM': '4220.00', 'HIREDATE': datetime.date(1995, 1, 1)})


1 comment:

ads