Last active
January 22, 2020 15:45
-
-
Save nakagami/016601a1fe7d5ca6e436bf8c466c66a5 to your computer and use it in GitHub Desktop.
Sample code to access DB2 via ibm_db by python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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