Skip to content

Instantly share code, notes, and snippets.

@nakagami nakagami/ibm_db_sample.py
Last active May 1, 2019

Embed
What would you like to do?
Sample code to access DB2 via ibm_db by python3
#!/usr/bin/env python3
import os
import ibm_db # pip install ibm_db
conn_s = "DATABASE={};".format(os.environ['DB2_DATABASE'])
conn_s += "HOSTNAME={};".format(os.environ['DB2_HOST'])
conn_s += "PORT={};".format(os.environ['DB2_PORT'])
conn_s += "PROTOCOL=TCPIP;"
conn_s += "UID={};".format(os.environ['DB2_USER'])
conn_s += "PWD={};".format(os.environ['DB2_PASSWORD'])
conn = ibm_db.connect(conn_s, "", "")
# execute immediate
try:
ibm_db.exec_immediate(conn, "DROP TABLE test")
except:
pass
ibm_db.exec_immediate(conn, """
CREATE TABLE test (
s VARCHAR(20),
i int,
d1 decimal(2, 1),
d2 decimal(11, 2))
""")
ibm_db.exec_immediate(conn, """
INSERT INTO test (s, i, d1, d2) VALUES
('abcdefghijklmnopq', 3, 1.1, 123456789.12),
('B', 2, 1.2, 2),
('C', 1, null, null)
""")
# prepare and execute
stmt = ibm_db.prepare(conn, "SELECT * FROM test")
ibm_db.execute(stmt)
row = ibm_db.fetch_tuple(stmt)
while row:
print(row)
row = ibm_db.fetch_tuple(stmt)
stmt = ibm_db.prepare(conn, "SELECT * FROM test where s=? and i=?")
ibm_db.execute(stmt, ("abcdefghijklmnopq", 3))
row = ibm_db.fetch_tuple(stmt)
assert row == ('abcdefghijklmnopq', 3, '1.1', '123456789.12')
assert ibm_db.fetch_tuple(stmt) is False
ibm_db.close(conn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.