简体   繁体   中英

Python code to list the active database from IBM UDB DB2

Could someone please help me in getting the list of active databases through python code from IBM DB2

There's more than one way to do it, but here is an example that uses a monitoring query. Your userid needs appropriate authorisation to run the query, refer to the documentation for details.

#!/usr/bin/python3
#
# the shell session that runs this script needs
# the correct environment variables to be already set
# (usually by dotting in the correct db2profile for the Db2 instance)
# otherwise ibm_db will fail to import citing load failure
# on a db2 library.
#
import sys
import ibm_db

db_user=''
db_name='sample'
db_pwd=''

try:
    ibm_db_conn = ibm_db.connect(db_name, db_user, db_pwd)
except:
    print('Failed to connect to database' + db_name)
    print(ibm_db.conn_errormsg())
    sys.exit(1)

try:
   action='Query snap_get_db'
   active_databases_query="SELECT db_name FROM TABLE(snap_get_db(NULL))"
   stmt_handle = ibm_db.exec_immediate(ibm_db_conn, active_databases_query)
   if  stmt_handle :
       action = 'Fetching resultSet returned by query'
       row = ibm_db.fetch_tuple(stmt_handle)
       while (row ):
          for i in row:
              print(i)
          row = ibm_db.fetch_tuple(stmt_handle)
   
except:
   print('Failed on ' + action)
   print(ibm_db.errormsg())
   sys.exit(1)  
   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM