Last active
April 17, 2020 17:51
-
-
Save data-henrik/6358b0b4d2044c6e2c7fab2f38fcd2fb to your computer and use it in GitHub Desktop.
Connect to Db2 on Cloud using an API key
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
import ibm_db | |
import pandas as pd | |
import ibm_db_dbi as dbi | |
import json,sys,os | |
def db2test(iamKey,hostname): | |
connstr="DATABASE=BLUDB;Authentication=GSSplugin;HOSTNAME={};PORT=50001;PROTOCOL=TCPIP;SECURITY=SSL;APIKEY={};".format(hostname,iamKey) | |
conn1 = dbi.connect(connstr) | |
# Quick test with Pandas and dataframe | |
df = pd.read_sql("select count(*) from syscat.tables", conn1) | |
return df.to_json(orient='split') | |
def main(args): | |
# Use API key from command parameter or Cloud Functions environment | |
iamKey = args.get("IAM_KEY") or os.environ.get('__OW_IAM_NAMESPACE_API_KEY') | |
db2host= args.get("DB2HOST") | |
db=json.loads(db2test(iamKey,db2host)) | |
return { **db} | |
# when testing, pass IAM_KEY and DB2HOST as JSON | |
if __name__ == '__main__': | |
print(main(json.loads(sys.argv[1]))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment