Could someone please help me in getting the list of active databases through python code from IBM DB2
Asked
Active
Viewed 114 times
-1
-
please check this [one](https://stackoverflow.com/questions/6044326/how-to-connect-python-to-db2) – gowridev Jun 02 '21 at 10:36
1 Answers
0
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)

mao
- 11,321
- 2
- 13
- 29