Skip to content

Instantly share code, notes, and snippets.

@data-henrik
Last active February 6, 2025 15:35
Show Gist options
  • Save data-henrik/9f5699378a86cd82007bb7b0a254e881 to your computer and use it in GitHub Desktop.
Save data-henrik/9f5699378a86cd82007bb7b0a254e881 to your computer and use it in GitHub Desktop.
Db2 and Python: Load data from or unload data to remote client using external table
import ibm_db
# connect to Db2 CE
conn_str='database=testdb2;hostname=localhost;port=50000;protocol=tcpip;uid=db2inst1;pwd=my_password'
ibm_db_conn = ibm_db.connect(conn_str,'','')
# create table if not yet present and make sure it is empty
ibm_db.exec_immediate(ibm_db_conn,'create table if not exists testcat(n varchar(128),s varchar(128))')
ibm_db.exec_immediate(ibm_db_conn,'delete from testcat')
# check that table is empty
res=ibm_db.exec_immediate(ibm_db_conn,'select count(*) from testcat')
if res is not None:
row = ibm_db.fetch_tuple(res)
if row is not None:
print("Count: {}\n".format(row[0]))
# load from local file on client to the (remote) Db2 server
ibm_db.exec_immediate(ibm_db_conn, "insert into testcat select * from external 'my_cat_tables.csv' using (REMOTESOURCE YES)")
# check that data was inserted
res=ibm_db.exec_immediate(ibm_db_conn,'select count(*) from testcat')
if res is not None:
row = ibm_db.fetch_tuple(res)
if row is not None:
print("Count: {}\n".format(row[0]))
# close connection
ibm_db.close(ibm_db_conn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment