From 0757327aba712988c76f6a983d71be500aa1b1f0 Mon Sep 17 00:00:00 2001 From: Vinayak Agrawal Date: Mon, 7 Oct 2019 22:26:25 -0700 Subject: [PATCH] Added Python Samples --- .../HTML_Documentation/ibm_db-active.html | 13347 +++++++++++++++ .../HTML_Documentation/ibm_db-autocommit.html | 13433 +++++++++++++++ .../HTML_Documentation/ibm_db-bind_param.html | 13499 +++++++++++++++ .../HTML_Documentation/ibm_db-callproc.html | 13412 +++++++++++++++ .../ibm_db-client_info.html | 13396 +++++++++++++++ .../HTML_Documentation/ibm_db-close.html | 13364 +++++++++++++++ .../ibm_db-column_privileges.html | 13465 +++++++++++++++ .../HTML_Documentation/ibm_db-columns.html | 13525 +++++++++++++++ .../HTML_Documentation/ibm_db-commit.html | 13434 +++++++++++++++ .../HTML_Documentation/ibm_db-conn_error.html | 13396 +++++++++++++++ .../ibm_db-conn_errormsg.html | 13396 +++++++++++++++ .../HTML_Documentation/ibm_db-connect.html | 13571 +++++++++++++++ .../HTML_Documentation/ibm_db-createdb.html | 13510 +++++++++++++++ .../HTML_Documentation/ibm_db-createdbNX.html | 13510 +++++++++++++++ .../ibm_db-cursor_type.html | 13462 +++++++++++++++ .../HTML_Documentation/ibm_db-dropdb.html | 13509 +++++++++++++++ .../ibm_db-exec_immediate.html | 13406 +++++++++++++++ .../HTML_Documentation/ibm_db-execute.html | 13420 +++++++++++++++ .../ibm_db-execute_many.html | 13411 +++++++++++++++ .../ibm_db-fetch_assoc.html | 13411 +++++++++++++++ .../HTML_Documentation/ibm_db-fetch_both.html | 13412 +++++++++++++++ .../HTML_Documentation/ibm_db-fetch_row.html | 13406 +++++++++++++++ .../ibm_db-fetch_tuple.html | 13411 +++++++++++++++ .../ibm_db-field_display_size.html | 13423 +++++++++++++++ .../HTML_Documentation/ibm_db-field_name.html | 13419 +++++++++++++++ .../HTML_Documentation/ibm_db-field_num.html | 13380 +++++++++++++++ .../ibm_db-field_precision.html | 13412 +++++++++++++++ .../ibm_db-field_scale.html | 13411 +++++++++++++++ .../HTML_Documentation/ibm_db-field_type.html | 13422 +++++++++++++++ .../ibm_db-field_width.html | 13411 +++++++++++++++ .../ibm_db-foreign_keys.html | 13507 +++++++++++++++ .../ibm_db-free_result.html | 13475 +++++++++++++++ .../HTML_Documentation/ibm_db-get_option.html | 13620 +++++++++++++++ .../ibm_db-next_result.html | 13535 +++++++++++++++ .../HTML_Documentation/ibm_db-num_fields.html | 13384 +++++++++++++++ .../HTML_Documentation/ibm_db-num_rows.html | 13443 +++++++++++++++ .../HTML_Documentation/ibm_db-pconnect.html | 13745 ++++++++++++++++ .../HTML_Documentation/ibm_db-prepare.html | 13426 +++++++++++++++ .../ibm_db-primary_keys.html | 13417 +++++++++++++++ .../ibm_db-procedure_columns.html | 13542 +++++++++++++++ .../HTML_Documentation/ibm_db-procedures.html | 13438 +++++++++++++++ .../HTML_Documentation/ibm_db-recreatedb.html | 13512 +++++++++++++++ .../HTML_Documentation/ibm_db-result.html | 13385 +++++++++++++++ .../HTML_Documentation/ibm_db-rollback.html | 13434 +++++++++++++++ .../ibm_db-server_info.html | 13563 +++++++++++++++ .../HTML_Documentation/ibm_db-set_option.html | 13732 +++++++++++++++ .../ibm_db-special_columns.html | 13462 +++++++++++++++ .../HTML_Documentation/ibm_db-statistics.html | 13513 +++++++++++++++ .../HTML_Documentation/ibm_db-stmt_error.html | 13388 +++++++++++++++ .../ibm_db-stmt_errormsg.html | 13389 +++++++++++++++ .../ibm_db-table_privileges.html | 13484 +++++++++++++++ .../HTML_Documentation/ibm_db-tables.html | 13434 +++++++++++++++ python_samples/HTML_Documentation/readme.md | 1 + .../Jupyter_Notebooks/ibm_db-active.ipynb | 258 + .../Jupyter_Notebooks/ibm_db-autocommit.ipynb | 342 + .../Jupyter_Notebooks/ibm_db-bind_param.ipynb | 407 + .../Jupyter_Notebooks/ibm_db-callproc.ipynb | 325 + .../ibm_db-client_info.ipynb | 303 + .../Jupyter_Notebooks/ibm_db-close.ipynb | 273 + .../ibm_db-column_privileges.ipynb | 375 + .../Jupyter_Notebooks/ibm_db-columns.ipynb | 435 + .../Jupyter_Notebooks/ibm_db-commit.ipynb | 344 + .../Jupyter_Notebooks/ibm_db-conn_error.ipynb | 302 + .../ibm_db-conn_errormsg.ipynb | 302 + .../Jupyter_Notebooks/ibm_db-connect.ipynb | 470 + .../Jupyter_Notebooks/ibm_db-createdb.ipynb | 414 + .../Jupyter_Notebooks/ibm_db-createdbNX.ipynb | 414 + .../ibm_db-cursor_type.ipynb | 379 + .../Jupyter_Notebooks/ibm_db-dropdb.ipynb | 412 + .../ibm_db-exec_immediate.ipynb | 313 + .../Jupyter_Notebooks/ibm_db-execute.ipynb | 331 + .../ibm_db-execute_many.ipynb | 322 + .../ibm_db-fetch_assoc.ipynb | 323 + .../Jupyter_Notebooks/ibm_db-fetch_both.ipynb | 324 + .../Jupyter_Notebooks/ibm_db-fetch_row.ipynb | 318 + .../ibm_db-fetch_tuple.ipynb | 323 + .../ibm_db-field_display_size.ipynb | 334 + .../Jupyter_Notebooks/ibm_db-field_name.ipynb | 330 + .../Jupyter_Notebooks/ibm_db-field_num.ipynb | 291 + .../ibm_db-field_precision.ipynb | 322 + .../ibm_db-field_scale.ipynb | 322 + .../Jupyter_Notebooks/ibm_db-field_type.ipynb | 333 + .../ibm_db-field_width.ipynb | 322 + .../ibm_db-foreign_keys.ipynb | 417 + .../ibm_db-free_result.ipynb | 386 + .../Jupyter_Notebooks/ibm_db-get_option.ipynb | 518 + .../ibm_db-next_result.ipynb | 447 + .../Jupyter_Notebooks/ibm_db-num_fields.ipynb | 295 + .../Jupyter_Notebooks/ibm_db-num_rows.ipynb | 352 + .../Jupyter_Notebooks/ibm_db-pconnect.ipynb | 645 + .../Jupyter_Notebooks/ibm_db-prepare.ipynb | 332 + .../ibm_db-primary_keys.ipynb | 328 + .../ibm_db-procedure_columns.ipynb | 444 + .../Jupyter_Notebooks/ibm_db-procedures.ipynb | 348 + .../Jupyter_Notebooks/ibm_db-recreatedb.ipynb | 415 + .../Jupyter_Notebooks/ibm_db-result.ipynb | 296 + .../Jupyter_Notebooks/ibm_db-rollback.ipynb | 344 + .../ibm_db-server_info.ipynb | 466 + .../Jupyter_Notebooks/ibm_db-set_option.ipynb | 631 + .../ibm_db-special_columns.ipynb | 368 + .../Jupyter_Notebooks/ibm_db-statistics.ipynb | 415 + .../Jupyter_Notebooks/ibm_db-stmt_error.ipynb | 295 + .../ibm_db-stmt_errormsg.ipynb | 295 + .../ibm_db-table_privileges.ipynb | 394 + .../Jupyter_Notebooks/ibm_db-tables.ipynb | 339 + .../Jupyter_Notebooks/ibm_db_tools.py | 360 + .../Jupyter_Notebooks/ipynb_exit.py | 86 + python_samples/Jupyter_Notebooks/readme.md | 19 + python_samples/LICENSE | 201 + .../Python_Examples/ibm_db/ibm_db-active.py | 87 + .../ibm_db/ibm_db-autocommit.py | 151 + .../ibm_db/ibm_db-bind_param.py | 174 + .../Python_Examples/ibm_db/ibm_db-callproc.py | 139 + .../ibm_db/ibm_db-client_info.py | 108 + .../Python_Examples/ibm_db/ibm_db-close.py | 105 + .../ibm_db/ibm_db-column_privileges.py | 146 + .../Python_Examples/ibm_db/ibm_db-columns.py | 177 + .../Python_Examples/ibm_db/ibm_db-commit.py | 162 + .../ibm_db/ibm_db-conn_error.py | 109 + .../ibm_db/ibm_db-conn_errormsg.py | 109 + .../ibm_db/ibm_db-connect_DB.py | 127 + .../ibm_db/ibm_db-connect_SERVER.py | 111 + .../ibm_db/ibm_db-createdbNX_LOCAL.py | 106 + .../ibm_db/ibm_db-createdbNX_REMOTE.py | 109 + .../ibm_db/ibm_db-createdb_LOCAL.py | 105 + .../ibm_db/ibm_db-createdb_REMOTE.py | 108 + .../ibm_db/ibm_db-cursor_type.py | 189 + .../ibm_db/ibm_db-dropdb_LOCAL.py | 106 + .../ibm_db/ibm_db-dropdb_REMOTE.py | 108 + .../ibm_db/ibm_db-exec_immediate.py | 116 + .../Python_Examples/ibm_db/ibm_db-execute.py | 144 + .../ibm_db/ibm_db-execute_many.py | 141 + .../ibm_db/ibm_db-fetch_assoc.py | 125 + .../ibm_db/ibm_db-fetch_both.py | 126 + .../ibm_db/ibm_db-fetch_row.py | 120 + .../ibm_db/ibm_db-fetch_tuple.py | 125 + .../ibm_db/ibm_db-field_display_size.py | 140 + .../ibm_db/ibm_db-field_name.py | 136 + .../ibm_db/ibm_db-field_num.py | 116 + .../ibm_db/ibm_db-field_precision.py | 139 + .../ibm_db/ibm_db-field_scale.py | 139 + .../ibm_db/ibm_db-field_type.py | 139 + .../ibm_db/ibm_db-field_width.py | 139 + .../ibm_db/ibm_db-foreign_keys.py | 192 + .../ibm_db/ibm_db-free_result.py | 202 + .../ibm_db/ibm_db-get_option_CONNECTION.py | 132 + .../ibm_db/ibm_db-get_option_STATEMENT.py | 136 + .../ibm_db/ibm_db-next_result.py | 242 + .../ibm_db/ibm_db-num_fields.py | 119 + .../Python_Examples/ibm_db/ibm_db-num_rows.py | 173 + .../ibm_db/ibm_db-pconnect_DB.py | 175 + .../ibm_db/ibm_db-pconnect_SERVER.py | 159 + .../Python_Examples/ibm_db/ibm_db-prepare.py | 136 + .../ibm_db/ibm_db-primary_keys.py | 134 + .../ibm_db/ibm_db-procedure_columns.py | 185 + .../ibm_db/ibm_db-procedures.py | 134 + .../ibm_db/ibm_db-recreatedb_LOCAL.py | 104 + .../ibm_db/ibm_db-recreatedb_REMOTE.py | 108 + .../Python_Examples/ibm_db/ibm_db-result.py | 112 + .../Python_Examples/ibm_db/ibm_db-rollback.py | 162 + .../ibm_db/ibm_db-server_info.py | 194 + .../ibm_db/ibm_db-set_option_CONNECTION.py | 155 + .../ibm_db/ibm_db-set_option_STATEMENT.py | 214 + .../ibm_db/ibm_db-special_columns.py | 157 + .../ibm_db/ibm_db-statistics.py | 160 + .../ibm_db/ibm_db-stmt_error.py | 97 + .../ibm_db/ibm_db-stmt_errormsg.py | 98 + .../ibm_db/ibm_db-table_privileges.py | 135 + .../Python_Examples/ibm_db/ibm_db-tables.py | 132 + .../Python_Examples/ibm_db/ibm_db_tools.py | 360 + .../Python_Examples/ibm_db/ipynb_exit.py | 86 + .../Python_Examples/ibm_db/readme.md | 9 + .../ibm_db_dbi/ibm_db_dbi-arraysize.py | 158 + .../ibm_db_dbi/ibm_db_dbi-callproc.py | 159 + .../ibm_db_dbi/ibm_db_dbi-close_CONNECTION.py | 96 + .../ibm_db_dbi/ibm_db_dbi-close_CURSOR.py | 157 + .../ibm_db_dbi/ibm_db_dbi-commit.py | 167 + .../ibm_db_dbi/ibm_db_dbi-connect_DB.py | 96 + .../ibm_db_dbi/ibm_db_dbi-cursor.py | 102 + .../ibm_db_dbi/ibm_db_dbi-description.py | 176 + .../ibm_db_dbi/ibm_db_dbi-execute.py | 147 + .../ibm_db_dbi/ibm_db_dbi-executemany.py | 149 + .../ibm_db_dbi/ibm_db_dbi-fetchall.py | 147 + .../ibm_db_dbi/ibm_db_dbi-fetchmany.py | 147 + .../ibm_db_dbi/ibm_db_dbi-fetchone.py | 145 + .../ibm_db_dbi/ibm_db_dbi-nextset.py | 270 + .../ibm_db_dbi/ibm_db_dbi-rollback.py | 167 + .../ibm_db_dbi/ibm_db_dbi-rowcount.py | 127 + .../ibm_db_dbi/ibm_db_dbi_tools.py | 90 + .../Python_Examples/ibm_db_dbi/readme.md | 9 + python_samples/Python_Examples/readme.md | 1 + python_samples/README.md | 59 + python_samples/_config.yml | 1 + 193 files changed, 730865 insertions(+) create mode 100644 python_samples/HTML_Documentation/ibm_db-active.html create mode 100644 python_samples/HTML_Documentation/ibm_db-autocommit.html create mode 100644 python_samples/HTML_Documentation/ibm_db-bind_param.html create mode 100644 python_samples/HTML_Documentation/ibm_db-callproc.html create mode 100644 python_samples/HTML_Documentation/ibm_db-client_info.html create mode 100644 python_samples/HTML_Documentation/ibm_db-close.html create mode 100644 python_samples/HTML_Documentation/ibm_db-column_privileges.html create mode 100644 python_samples/HTML_Documentation/ibm_db-columns.html create mode 100644 python_samples/HTML_Documentation/ibm_db-commit.html create mode 100644 python_samples/HTML_Documentation/ibm_db-conn_error.html create mode 100644 python_samples/HTML_Documentation/ibm_db-conn_errormsg.html create mode 100644 python_samples/HTML_Documentation/ibm_db-connect.html create mode 100644 python_samples/HTML_Documentation/ibm_db-createdb.html create mode 100644 python_samples/HTML_Documentation/ibm_db-createdbNX.html create mode 100644 python_samples/HTML_Documentation/ibm_db-cursor_type.html create mode 100644 python_samples/HTML_Documentation/ibm_db-dropdb.html create mode 100644 python_samples/HTML_Documentation/ibm_db-exec_immediate.html create mode 100644 python_samples/HTML_Documentation/ibm_db-execute.html create mode 100644 python_samples/HTML_Documentation/ibm_db-execute_many.html create mode 100644 python_samples/HTML_Documentation/ibm_db-fetch_assoc.html create mode 100644 python_samples/HTML_Documentation/ibm_db-fetch_both.html create mode 100644 python_samples/HTML_Documentation/ibm_db-fetch_row.html create mode 100644 python_samples/HTML_Documentation/ibm_db-fetch_tuple.html create mode 100644 python_samples/HTML_Documentation/ibm_db-field_display_size.html create mode 100644 python_samples/HTML_Documentation/ibm_db-field_name.html create mode 100644 python_samples/HTML_Documentation/ibm_db-field_num.html create mode 100644 python_samples/HTML_Documentation/ibm_db-field_precision.html create mode 100644 python_samples/HTML_Documentation/ibm_db-field_scale.html create mode 100644 python_samples/HTML_Documentation/ibm_db-field_type.html create mode 100644 python_samples/HTML_Documentation/ibm_db-field_width.html create mode 100644 python_samples/HTML_Documentation/ibm_db-foreign_keys.html create mode 100644 python_samples/HTML_Documentation/ibm_db-free_result.html create mode 100644 python_samples/HTML_Documentation/ibm_db-get_option.html create mode 100644 python_samples/HTML_Documentation/ibm_db-next_result.html create mode 100644 python_samples/HTML_Documentation/ibm_db-num_fields.html create mode 100644 python_samples/HTML_Documentation/ibm_db-num_rows.html create mode 100644 python_samples/HTML_Documentation/ibm_db-pconnect.html create mode 100644 python_samples/HTML_Documentation/ibm_db-prepare.html create mode 100644 python_samples/HTML_Documentation/ibm_db-primary_keys.html create mode 100644 python_samples/HTML_Documentation/ibm_db-procedure_columns.html create mode 100644 python_samples/HTML_Documentation/ibm_db-procedures.html create mode 100644 python_samples/HTML_Documentation/ibm_db-recreatedb.html create mode 100644 python_samples/HTML_Documentation/ibm_db-result.html create mode 100644 python_samples/HTML_Documentation/ibm_db-rollback.html create mode 100644 python_samples/HTML_Documentation/ibm_db-server_info.html create mode 100644 python_samples/HTML_Documentation/ibm_db-set_option.html create mode 100644 python_samples/HTML_Documentation/ibm_db-special_columns.html create mode 100644 python_samples/HTML_Documentation/ibm_db-statistics.html create mode 100644 python_samples/HTML_Documentation/ibm_db-stmt_error.html create mode 100644 python_samples/HTML_Documentation/ibm_db-stmt_errormsg.html create mode 100644 python_samples/HTML_Documentation/ibm_db-table_privileges.html create mode 100644 python_samples/HTML_Documentation/ibm_db-tables.html create mode 100644 python_samples/HTML_Documentation/readme.md create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-active.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-autocommit.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-bind_param.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-callproc.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-client_info.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-close.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-column_privileges.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-columns.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-commit.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-conn_error.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-conn_errormsg.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-connect.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-createdb.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-createdbNX.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-cursor_type.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-dropdb.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-exec_immediate.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-execute.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-execute_many.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-fetch_assoc.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-fetch_both.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-fetch_row.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-fetch_tuple.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-field_display_size.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-field_name.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-field_num.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-field_precision.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-field_scale.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-field_type.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-field_width.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-foreign_keys.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-free_result.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-get_option.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-next_result.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-num_fields.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-num_rows.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-pconnect.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-prepare.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-primary_keys.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-procedure_columns.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-procedures.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-recreatedb.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-result.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-rollback.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-server_info.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-set_option.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-special_columns.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-statistics.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-stmt_error.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-stmt_errormsg.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-table_privileges.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db-tables.ipynb create mode 100644 python_samples/Jupyter_Notebooks/ibm_db_tools.py create mode 100644 python_samples/Jupyter_Notebooks/ipynb_exit.py create mode 100644 python_samples/Jupyter_Notebooks/readme.md create mode 100644 python_samples/LICENSE create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-active.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-autocommit.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-bind_param.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-callproc.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-client_info.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-close.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-column_privileges.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-columns.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-commit.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-conn_error.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-conn_errormsg.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-connect_DB.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-connect_SERVER.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-createdbNX_LOCAL.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-createdbNX_REMOTE.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-createdb_LOCAL.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-createdb_REMOTE.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-cursor_type.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-dropdb_LOCAL.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-dropdb_REMOTE.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-exec_immediate.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-execute.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-execute_many.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-fetch_assoc.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-fetch_both.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-fetch_row.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-fetch_tuple.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-field_display_size.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-field_name.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-field_num.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-field_precision.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-field_scale.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-field_type.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-field_width.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-foreign_keys.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-free_result.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-get_option_CONNECTION.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-get_option_STATEMENT.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-next_result.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-num_fields.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-num_rows.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-pconnect_DB.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-pconnect_SERVER.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-prepare.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-primary_keys.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-procedure_columns.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-procedures.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-recreatedb_LOCAL.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-recreatedb_REMOTE.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-result.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-rollback.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-server_info.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-set_option_CONNECTION.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-set_option_STATEMENT.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-special_columns.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-statistics.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-stmt_error.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-stmt_errormsg.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-table_privileges.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db-tables.py create mode 100644 python_samples/Python_Examples/ibm_db/ibm_db_tools.py create mode 100644 python_samples/Python_Examples/ibm_db/ipynb_exit.py create mode 100644 python_samples/Python_Examples/ibm_db/readme.md create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-arraysize.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-callproc.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-close_CONNECTION.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-close_CURSOR.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-commit.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-connect_DB.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-cursor.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-description.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-execute.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-executemany.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchall.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchmany.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchone.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-nextset.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-rollback.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-rowcount.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi_tools.py create mode 100644 python_samples/Python_Examples/ibm_db_dbi/readme.md create mode 100644 python_samples/Python_Examples/readme.md create mode 100644 python_samples/README.md create mode 100644 python_samples/_config.yml diff --git a/python_samples/HTML_Documentation/ibm_db-active.html b/python_samples/HTML_Documentation/ibm_db-active.html new file mode 100644 index 0000000..0735f4a --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-active.html @@ -0,0 +1,13347 @@ + + + + +ibm_db-active + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.active()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Determine whether the Db2 server or database connection specified is active.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.active( IBM_DBConnectionconnection)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server or database connection.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • True      : The Db2 server or database connection specified is active.
  • +
  • False    : The Db2 server or database connection specified is not active.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.active() API is used to determine if a Db2 server or database connection that was established using the ibm_db.connect() API or ibm_db.pconnect() is active.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-active.py                                                                  #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.active() API.        #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Determine Whether The Current Database Connection Is Active Or Inactive
+try:
+    connState = ibm_db.active(dbConnection)
+except Exception:
+    pass
+
+# Display A Status Message That Shows The Current Connection State
+print("The connection to the " + dbName + " database is ", end="")
+if connState is True:
+    print("ACTIVE.\n")
+elif connState is False:
+    print("NOT ACTIVE.\n")
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+The connection to the SAMPLE database is ACTIVE.
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-autocommit.html b/python_samples/HTML_Documentation/ibm_db-autocommit.html new file mode 100644 index 0000000..20dde7f --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-autocommit.html @@ -0,0 +1,13433 @@ + + + + +ibm_db-autocommit + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.autocommit()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Determine or set the AUTOCOMMIT behavior of a Db2 server or database connection.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

mixed ibm_db.autocommit( IBM_DBConnectionconnection[, boolsetting] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server or database connection.
  • +
  • setting            : A constant that specifies whether auto-commit behavior is to be used. Valid values are:

    +
      +
    • ibm_db.SQL_AUTOCOMMIT_OFF  : Do not use auto-commit behavior; require applications to end transactions by calling either the ibm_db.commit() or the ibm_db.rollback() API.
    • +
    • ibm_db.SQL_AUTOCOMMIT_ON    : Use auto-commit behavior.
    • +
    +
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+

When a setting value is provided:

+
    +
  • True      : AUTOCOMMIT behavior was successfully set to the setting specified.
  • +
  • False    : AUTOCOMMIT behavior was not set to the setting specified.
  • +
+ +
+
+
+
+
+
+

When a setting value is not provided:

+
    +
  • 0      : AUTOCOMMIT behavior is OFF.
  • +
  • 1      : AUTOCOMMIT behavior is ON.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.autocommit() API can be used to determine if a Db2 server or database connection (that was established by calling the ibm_db.connect() or ibm_db.pconnect() API) is configured for AUTOCOMMIT behavior. It can also be used to turn AUTOCOMMIT behavior for a Db2 server or database connection OFF or ON.

AUTOCOMMIT behavior controls when transactions performing SQL operations against a database are made permanent (committed) or are backed out (rolled back). If AUTOCOMMIT behavior is turned ON, transactions are committed automatically, immediately after they are executed. (In other words, each SQL operation is treated as a single transaction and when the operation completes, changes made to the database are made permanent.) If AUTOCOMMIT behavior is turned OFF, transactions must be manually terminated by executing either the ibm_db.commit() or the ibm_db.rollback() API.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-autocommit.py                                                              #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.autocommit() API.    #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.connect()                                                             #
+#                 ibm_db.close()                                                               #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+connOption = {ibm_db.SQL_ATTR_AUTOCOMMIT: ibm_db.SQL_AUTOCOMMIT_ON}
+dbConnection = None
+
+# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database
+# Is About To Be Made
+print("\nConnecting to the \'" + dbName + "\' database ... ", end="")
+
+# Construct The String That Will Be Used To Establish A Db2 Database Connection
+connString = "ATTACH=FALSE"              # Attach To A Database; Not A Server
+connString += ";DATABASE=" + dbName      # Required To Connect To A Database     
+connString += ";PROTOCOL=TCPIP"
+connString += ";UID=" + userID
+connString += ";PWD=" + passWord
+
+# Attempt To Establish A Connection To The Database Specified
+try:
+    dbConnection = ibm_db.connect(connString, '', '', connOption)
+except Exception:
+    pass
+
+# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit
+if dbConnection is None:
+    print("\nERROR: Unable to connect to the \'" + dbName + "\' database.")
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Determine Whether Autocommit Behavior Is OFF or ON (Should Match The connOption Setting)
+try:
+    returnCode = ibm_db.autocommit(dbConnection)
+except Exception:
+    pass
+
+# If Autocommit Behavior Is OFF, Turn It ON
+if returnCode is 0:
+    print("AUTOCOMMIT behavior is OFF; turning it ON ... ", end="")
+    try:
+        returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_ON)
+    except Exception:
+        pass
+    
+    # If AUTOCOMMIT Behavior Could Not Be Turned ON, Display An Error Message And Continue
+    if returnCode is False:
+        print("\nERROR: Unable to turn AUTOCOMMIT behavior ON.")
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!\n")
+
+# If Autocommit Behavior Is ON, Turn It OFF
+elif returnCode is 1:
+    print("AUTOCOMMIT behavior is ON; turning it OFF ... ", end="")
+    try:
+        returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_OFF)
+    except Exception:
+        pass
+
+    # If AUTOCOMMIT Behavior Could Not Be Turned OFF, Display An Error Message And Continue
+    if returnCode is False:
+        print("\nERROR: Unable to turn AUTOCOMMIT behavior OFF.")
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!\n")
+
+# Check Autocommit Behavior Again And Display Its Status
+try:
+    returnCode = ibm_db.autocommit(dbConnection)
+except Exception:
+    pass
+
+if returnCode is 0:
+    print("AUTOCOMMIT behavior is now OFF.\n")
+elif returnCode is 1:
+    print("AUTOCOMMIT behavior is now ON.\n")
+
+# Attempt To Close The Db2 Database Connection That Was Opened Earlier
+if not dbConnection is None:
+    print("Disconnecting from the \'" + dbName + "\' database ... ", end="")
+    try:
+        returnCode = ibm_db.close(dbConnection)
+    except Exception:
+        pass
+
+    # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit
+    if returnCode is False:
+        print("\nERROR: Unable to disconnect from the " + dbName + " database.")
+        exit(-1)
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!\n")
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the 'SAMPLE' database ... Done!
+
+AUTOCOMMIT behavior is ON; turning it OFF ... Done!
+
+AUTOCOMMIT behavior is now OFF.
+
+Disconnecting from the 'SAMPLE' database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-bind_param.html b/python_samples/HTML_Documentation/ibm_db-bind_param.html new file mode 100644 index 0000000..8d5e2fb --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-bind_param.html @@ -0,0 +1,13499 @@ + + + + +ibm_db-bind_param + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.bind_param()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Associate (bind) parameter markers coded in a prepared SQL statement with application variables.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.bind_param( IBM_DBStatementpreparedStmt,intparamNumber,stringvariable
[, intparamType[, intdataType[, intprecision[, intscale[, intsize] ] ] ] ] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • preparedStmt     : A prepared SQL statement (returned by the ibm_db.prepare() API).
  • +
  • paramNumber    : The parameter marker's location in the SQL statement text. Parameter markers are numbered sequentially, from left to right as they appear in the statement, starting with 1.
  • +
  • variable              : The variable to be bound to the parameter marker specified in the paramNumber parameter.
  • +
  • paramType         : The type of parameter marker being bound. Valid values are:

    +
      +
    • ibm_db.SQL_PARAM_INPUT                 : The parameter marker is associated with an SQL statement other than a CALL statement or the parameter marker is associated with an input parameter of a stored procedure being called.
    • +
    • ibm_db.SQL_PARAM_OUTPUT               : The parameter marker is associated with an output parameter or the return value of a stored procedure being called.
    • +
    • ibm_db.SQL_PARAM_INPUT_OUTPUT   : The parameter marker is associated with an input/output parameter of a stored procedure being called.
    • +
    • ibm_db.PARAM_FILE                           : The parameter marker is associated with a file that contains the data that will be provided when the SQL statement is executed. (A file can be used to avoid having to store large object data in memory.)

    • +
    +
  • +
  • dataType             : The SQL data type the application variable specified in the variable parameter should be bound as. Valid values are:

    +
      +
    • ibm_db.SQL_BINARY   : The variable should be bound as a binary large object.
    • +
    • ibm_db.SQL_CHAR       : The variable should be bound as fixed-length character string.
    • +
    • ibm_db.SQL_DOUBLE   : The variable should be bound as a double-precision floating-point number.
    • +
    • ibm_db.SQL_LONG       : The variable should be bound as a long varying-length character string.

    • +
    +
  • +
  • precision           : The precision (i.e., total number of digits) of the application variable used.

    +
  • +
  • scale                  : The scale (i.e., number of decimal digits) of the application variable used.
  • +
  • size                    : The size of the memory buffer used to store the value associated with the parameter marker.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • True      : The bind operation was successfull.
  • +
  • False    : The bind operation failed.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.bind_param() API is used to associate (bind) parameter markers in an SQL statement to application variables - a parameter marker is represented by a question mark character (?) and is used to indicate the position in an SQL statement where an application-supplied value is to be substituted when the statement is executed.

+

This API gives you more control over the parameter type (inout, output, or input/output), SQL data type, precision, and scale that is used for parameter marker values as opposed to passing values via an input tuple when the ibm_db.execute() API is used.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-bind_param.py                                                              #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.bind_param() API.    #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.prepare()                                                             #
+#                 ibm_db.execute()                                                             #
+#                 ibm_db.fetch_tuple()                                                         #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.active() API.        #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+preparedStmt = None
+deptID = ['B01', 'C01', 'D01', 'E01']
+returnCode = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed - Include A Parameter Marker
+sqlStatement = "SELECT projname FROM project WHERE deptno = ?"
+
+# Prepare The SQL Statement Just Defined
+print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit
+if preparedStmt is False:
+    print("\nERROR: Unable to prepare the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# For Every Value Specified In The deptID List, ...
+for loopCounter in range(0, 4):
+
+    # Display A Message That Identifies The Query Being Executed
+    print("Processing query " + str(loopCounter + 1) + ":")
+
+    # Assign A Value To The Application Variable That Is To Be Bound To The SQL Statement
+    paramValue = deptID[loopCounter]
+
+    # Bind The Application Variable To The Parameter Marker Used In The SQL Statement 
+    print("  Binding the appropriate variable to the parameter marker used ... ", end="")
+    try:
+        returnCode = ibm_db.bind_param(preparedStmt, 1, paramValue, ibm_db.SQL_PARAM_INPUT,
+                         ibm_db.SQL_CHAR)
+    except Exception:
+        pass
+    
+    # If The Application Variable Was Not Bound Successfully, Display An Error Message And Exit
+    if returnCode is False:
+        print("\nERROR: Unable to bind the variable to the parameter marker specified.")
+        conn.closeConnection()
+        exit(-1)
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!")
+
+    # Execute The Prepared SQL Statement (Using The New Parameter Marker Value)
+    print("  Executing the prepared SQL statement ", end="")
+    print("(with the value \'" + paramValue + "\') ... ", end="")
+    try:
+        returnCode = ibm_db.execute(preparedStmt)
+    except Exception:
+        pass
+   
+    # If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+    if returnCode is False:
+        print("\nERROR: Unable to execute the SQL statement.")
+        conn.closeConnection()
+        exit(-1)
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!")
+
+    # Display A Report Header
+    print("Results:\n")
+    print("DEPTNO  PROJNAME")
+    print("______  _____________________")
+
+    # As Long As There Are Records, ...
+    noData = False
+    while noData is False:
+
+        # Retrieve A Record And Store It In A Python Tuple
+        try:
+            dataRecord = ibm_db.fetch_tuple(preparedStmt)
+        except:
+            pass
+
+        # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The
+        # "No Data" Flag And Continue 
+        if dataRecord is False:
+            noData = True
+
+        # Otherwise, Format And Display The Data Retrieved
+        else:
+            print("{:<6}  {}" .format(paramValue, dataRecord[0])) 
+
+    # Add A Blank Line To The End Of The Report
+    print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Preparing the SQL statement "SELECT projname FROM project WHERE deptno = ?" ... Done!
+
+Processing query 1:
+  Binding the appropriate variable to the parameter marker used ... Done!
+  Executing the prepared SQL statement (with the value 'B01') ... Done!
+Results:
+
+DEPTNO  PROJNAME
+______  _____________________
+B01     WELD LINE PLANNING
+
+Processing query 2:
+  Binding the appropriate variable to the parameter marker used ... Done!
+  Executing the prepared SQL statement (with the value 'C01') ... Done!
+Results:
+
+DEPTNO  PROJNAME
+______  _____________________
+C01     QUERY SERVICES
+C01     USER EDUCATION
+
+Processing query 3:
+  Binding the appropriate variable to the parameter marker used ... Done!
+  Executing the prepared SQL statement (with the value 'D01') ... Done!
+Results:
+
+DEPTNO  PROJNAME
+______  _____________________
+D01     ADMIN SERVICES
+D01     WELD LINE AUTOMATION
+
+Processing query 4:
+  Binding the appropriate variable to the parameter marker used ... Done!
+  Executing the prepared SQL statement (with the value 'E01') ... Done!
+Results:
+
+DEPTNO  PROJNAME
+______  _____________________
+E01     OPERATION SUPPORT
+E01     GEN SYSTEMS SERVICES
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-callproc.html b/python_samples/HTML_Documentation/ibm_db-callproc.html new file mode 100644 index 0000000..201112d --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-callproc.html @@ -0,0 +1,13412 @@ + + + + +ibm_db-callproc + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.callproc()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Call (execute) a stored procedure.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

[IBM_DBStatement | tuple] ibm_db.callproc( IBM_DBConnectionconnection,stringprocName,[, tupleprocParams] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection     : A valid Db2 database connection.
  • +
  • procName       : The name of a stored procedure that exists in the connected database.
  • +
  • procParams    : A tuple containing values (or value placeholders) for each parameter required by the procedure.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an IBM_DBStatement object or a tuple containing an IBM_DBStatement object, followed by the parameter values that were supplied for the procPrams parameter.
  • +
  • If unsuccessful, the value None.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.callproc() API is used to execute a stored procedure that has been defined in the database the application is currently connected to. If the stored procedure expects IN, OUT, and/or INOUT parameter values, a tuple that contains a value for each parameter defined must be supplied (via the procParams parameter).

+

Upon successful execution of the procedure invoked, a tuple containing an IBM_DBStatement object and a modified copy of the parameter values supplied is returned. Values for IN parameters are left untouched whereas values for OUT and INOUT parameters may have been changed by the procedure. (If the procedure did not have any parameters defined, only an IBM_DBStatement object will be returned.)

+

A call to a stored procedure can return zero or more result sets; if a result set is returned, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-callproc.py                                                                #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.callproc() API.      #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+spName = "SALARY_STATS"
+returnCode = False
+spParamValues = (0.0, 0.0, 0.0)
+resultSet = None
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Used To Create A New Stored Procedure
+sqlStatement = "CREATE OR REPLACE PROCEDURE " + spName
+sqlStatement += "  (OUT maxSalary DOUBLE, OUT minSalary DOUBLE, OUT avgSalary DOUBLE) "
+sqlStatement += "LANGUAGE SQL "
+sqlStatement += "DYNAMIC RESULT SETS 0 "
+sqlStatement += "READS SQL DATA "
+sqlStatement += "NO EXTERNAL ACTION "
+sqlStatement += "BEGIN"
+sqlStatement += "  SELECT MAX(salary) INTO maxSalary FROM employee; "
+sqlStatement += "  SELECT MIN(salary) INTO minSalary FROM employee; "
+sqlStatement += "  SELECT AVG(salary) INTO avgSalary FROM employee; "
+sqlStatement += "END"
+
+# Execute The SQL Statement Just Defined
+print("Creating an SQL stored procedure named \"" + spName + "\" ... ", end="")
+try:
+    returnCode = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Execute The Stored Procedure Just Created
+print("Executing the " + spName + " stored procedure ... ", end="")
+try:
+    resultSet = ibm_db.callproc(dbConnection, spName, spParamValues)
+except Exception:
+    pass
+
+# If The Stored Procedure Specified Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is None:
+    print("\nERROR: Unable to execute the stored procedure specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message; Then Format And Display The Data Values Returned
+else:
+    print("Done!\n")
+
+    # Display A Report Header
+    print("Salary statistics:")
+    print("______________________________")
+
+    # Display The Data Values Returned By The Stored Procedure
+    print("Highest salary   : ${:>10.2f}" .format(resultSet[1]))
+    print("Lowest salary    : ${:>10.2f}" .format(resultSet[2]))
+    print("Average salary   : ${:>10.2f}" .format(resultSet[3]))
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Creating an SQL stored procedure named "SALARY_STATS" ... Done!
+
+Executing the SALARY_STATS stored procedure ... Done!
+
+Salary statistics:
+______________________________
+Highest salary   : $ 152750.00
+Lowest salary    : $  31840.00
+Average salary   : $  58155.36
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-client_info.html b/python_samples/HTML_Documentation/ibm_db-client_info.html new file mode 100644 index 0000000..324126b --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-client_info.html @@ -0,0 +1,13396 @@ + + + + +ibm_db-client_info + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.client_info()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Obtain information about an IBM Db2 client.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

PyTypeObject ibm_db.client_info( IBM_DBConnectionconnection)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 client/server connection.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, a PyTypeObject populated with the following information:

    +
      +
    • APPL_CODEPAGE                 : The application code page used.
    • +
    • CONN_CODEPAGE                 : The code page used for the current connection.
    • +
    • DATA_SOURCE_NAME           : The data source name (DSN) used to create the current connection.
    • +
    • DRIVER_NAME                     : The name of the library that implements Db2 Call Level Interface (CLI) functionality.
    • +
    • DRIVER_ODBC_VER             : The version of Open Database Connectivity (ODBC) the client supports.
    • +
    • DRIVER_VER                       : The version of the Db2 client software that is running on the connected workstation, in the form of a string that has the format VV.RR.MMFF, where VV is the major version number, RR is the release number, MM is the modification number, and FF is the fix pack number. For example, "11.01.0404" represents version 11, release 1, modification 4, fix pack 4.
    • +
    • ODBC_SQL_CONFORMANCE   : The type of ODBC SQL grammar the client supports. Valid values are:

        +
      • MINIMAL   : The client supports the minimum amount of ODBC SQL grammar.
      • +
      • CORE         : The client supports the core ODBC SQL grammar.
      • +
      • EXTENDED : The client supports extended ODBC SQL grammar.

      • +
      +
    • +
    • ODBC_VER                           : The version of ODBC that the ODBC driver supports.

    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.client_info() API is used to obtain basic information about an IBM Db2 database client workstation.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-client_info.py                                                             #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.client_info() API.   #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+svrConnection = None
+clientInfo = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server
+conn = Db2ConnectionMgr('SERVER', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    svrConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Obtain Information About The Db2 Client Being Used
+print("Obtaining information about the Db2 client ... ", end="")
+try:
+    clientInfo = ibm_db.client_info(svrConnection)
+except Exception:
+    pass
+
+# If Information About The Client Could Not Be Obtained, Display An Error Message 
+if clientInfo is False:
+    print("\nERROR: Unable to obtain Db2 client information.\n")
+
+# Otherwise, Complete The Status Message; Then Format And Display The Data Retrieved
+else:
+    print("Done!\n")
+
+    # Display A Report Header
+    print("Client details:")
+    print("____________________________________________________________________")
+
+    # Display The Client Data
+    print("Application code page        : {}" .format(clientInfo.APPL_CODEPAGE))
+    print("Current connection code page : {}" .format(clientInfo.CONN_CODEPAGE))
+    print("Data source name (DSN)       : {}" .format(clientInfo.DATA_SOURCE_NAME))
+    print("Driver name                  : {}" .format(clientInfo.DRIVER_NAME))
+    print("Driver version               : {}" .format(clientInfo.DRIVER_VER))
+    print("ODBC version supported       : {}" .format(clientInfo.DRIVER_ODBC_VER))
+    print("ODBC SQL conformance level   : ", end="")
+    if clientInfo.ODBC_SQL_CONFORMANCE == 'MINIMAL':
+        print("Supports the minimum ODBC SQL grammar\n")
+    elif clientInfo.ODBC_SQL_CONFORMANCE == 'CORE':
+        print("Supports the core ODBC SQL grammar\n")
+    elif clientInfo.ODBC_SQL_CONFORMANCE == 'EXTENDED':
+        print("Supports extended ODBC SQL grammar\n")
+
+# Close The Server Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the ibm-UDOO-x86 server ... Done!
+
+Obtaining information about the Db2 client ... Done!
+
+Client details:
+____________________________________________________________________
+Application code page        : 1208
+Current connection code page : 1208
+Data source name (DSN)       : SAMPLE
+Driver name                  : libdb2.a
+Driver version               : 11.01.0404
+ODBC version supported       : 03.51
+ODBC SQL conformance level   : Supports extended ODBC SQL grammar
+
+Disconnecting from the ibm-UDOO-x86 server ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-close.html b/python_samples/HTML_Documentation/ibm_db-close.html new file mode 100644 index 0000000..3992126 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-close.html @@ -0,0 +1,13364 @@ + + + + +ibm_db-close + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.close()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Close an open IBM DB2 server or database connection and if appropriate, return it to a connection pool.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.close( IBM_DBConnectionconnection)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server or database connection.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • True      : The Db2 server or database connection specified was closed.
  • +
  • False    : The Db2 server or database connection specified was not closed.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.close() API is used to close an open Db2 server or database connection. If this API is used to close a connection that was opened by the ibm_db.connect() API, the specified connection is terminated and all associated resources are returned to the server. However, if it is used to close a persistent connection that was created with the ibm_db.pconnect() API, the connection is returned to a connection pool, where it can be reused by the next ibm_db.pconnect() API call made.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-close.py                                                                   #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.close() API.         #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.connect()                                                             #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+returnCode = False
+
+# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database
+# Is About To Be Made
+print("\nConnecting to the \'" + dbName + "\' database ... ", end="")
+
+# Construct The String That Will Be Used To Establish A Db2 Database Connection
+connString = "ATTACH=FALSE"              # Attach To A Database; Not A Server
+connString += ";DATABASE=" + dbName      # Required To Connect To A Database     
+connString += ";PROTOCOL=TCPIP"
+connString += ";UID=" + userID
+connString += ";PWD=" + passWord
+
+# Attempt To Establish A Connection To The Database Specified
+try:
+    dbConnection = ibm_db.connect(connString, '', '')
+except Exception:
+    pass
+
+# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit
+if dbConnection is None:
+    print("\nERROR: Unable to connect to the \'" + dbName + "\' database.")
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+
+# Add Additional Db2 Database-Related Processing Here ...
+
+
+# Attempt To Close The Db2 Database Connection That Was Just Opened
+if not dbConnection is None:
+    print("Disconnecting from the \'" + dbName + "\' database ... ", end="")
+    try:
+        returnCode = ibm_db.close(dbConnection)
+    except Exception:
+        pass
+
+    # If The Database Connection Was Not Closed, Display An Error Message And Exit
+    if returnCode is False:
+        print("\nERROR: Unable to disconnect from the " + dbName + " database.")
+        exit(-1)
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!\n")
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the 'SAMPLE' database ... Done!
+
+Disconnecting from the 'SAMPLE' database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-column_privileges.html b/python_samples/HTML_Documentation/ibm_db-column_privileges.html new file mode 100644 index 0000000..d30e18b --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-column_privileges.html @@ -0,0 +1,13465 @@ + + + + +ibm_db-column_privileges + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.column_privileges()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve a list of columns and their associated privileges, for a given table.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.column_privileges( IBM_DBConnectionconnection[, stringqualifierName[, stringschemaName[, stringtableName[, stringcolumnName] ] ] ] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection        : A valid Db2 server or database connection.
  • +
  • qualifierName    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value None or an empty string ('') for Db2 databases on other operating systems.
  • +
  • schemaName     : The name of the schema that contains the table(s) that column privilege information is to be obtained for. To match all schemas, provide the value None or an empty string.
  • +
  • tableName          : The name of the table(s) and/or view(s) that column privilege information is to be obtained for. To match all tables and views, provide the value None or an empty string.
  • +
  • columnName      : The name of the column that privilege information is to be obtained for. To match all columns, provide the value None or an empty string.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an IBM_DBStatement with a result set that contains the following information:

    +
      +
    • TABLE_CAT        : The name of the catalog associated with the schema and table the column privilege is for; Db2 does not use catalogs so this field will always contain the value None. (Db2 databases on OS/390 or z/OS servers can return information in this field.)
    • +
    • TABLE_SCHEM    : The name of the schema for the table or view the privilege is associated with.
    • +
    • TABLE_NAME      : The name of the table or view the privilege is associated with.
    • +
    • COLUMN_NAME    : The name of the column the privilege is associated with.
    • +
    • PRIVILEGE        : The column privilege (INSERT, UPDATE, DELETE, SELECT, etc.).
    • +
    • GRANTOR            : The authorization ID of the user who granted the privilege.
    • +
    • GRANTEE            : The authorization ID of the user to whom the privilege was granted.
    • +
    • IS_GRANTABLE  : Indication of whether the authorization ID of the user to whom the privilege was granted (the GRANTEE) is permitted to grant the privilege to others. Valid values are YES and NO.

    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.column_privileges() API is used to retrieve a list of columns and the privileges associated with them, for one or more tables and/or views.

+

The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-column_privileges.py                                                       #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.column_privileges()  #
+#            API.                                                                              #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.fetch_assoc()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+schemaName = userID.upper()
+tableName = "PROJECT"
+columnName = "PROJNO"
+resultSet = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Retrieve Information About All Of The Column Privileges That Have Been Defined For 
+# The Table Specified
+print("Obtaining information about column privileges that exist for the " + columnName, end="")
+print(" column\nof the " +schemaName + "." + tableName + " table ... ", end="")
+try:
+    resultSet = ibm_db.column_privileges(dbConnection, None, schemaName, tableName, columnName)
+except Exception:
+    pass
+
+# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit
+if resultSet is False:
+    print("\nERROR: Unable to obtain the information desired.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# As Long As There Are Records (That Were Produced By The ibm_db.column_privileges API), ... 
+noData = False
+loopCounter = 1
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop 
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Information Retrieved
+    else:
+
+        #--------------------------------------------------------------------------------------#
+        # NOTE: The column name parameter value specified with the ibm_db.column_privileges()  #
+        # API appears to be ignored; if you only want to see column privilege information for  #
+        # a specific column, you will need to use the following filtering code:                #
+        if dataRecord['COLUMN_NAME'] != columnName:
+            continue
+        #--------------------------------------------------------------------------------------#
+
+        # Display Record Header Information
+        print("Column privilege " + str(loopCounter) + " details:")
+        print("___________________________________")
+
+        # Display The Information Stored In The Data Record Retrieved
+        print("Schema name            : {}" .format(dataRecord['TABLE_SCHEM']))
+        print("Table name             : {}" .format(dataRecord['TABLE_NAME']))
+        print("Column name            : {}" .format(dataRecord['COLUMN_NAME']))
+        print("Privilege grantor      : {}" .format(dataRecord['GRANTOR']))
+        print("Privilege recipient    : {}" .format(dataRecord['GRANTEE']))
+        print("Privilege              : {}" .format(dataRecord['PRIVILEGE']))
+        print("Privilege is grantable : {}" .format(dataRecord['IS_GRANTABLE']))
+
+        # Increment The loopCounter Variable And Print A Blank Line To Separate Column The
+        # Records From Each Other
+        loopCounter += 1
+        print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Obtaining information about column privileges that exist for the PROJNO column
+of the DB2INST1.PROJECT table ... Done!
+
+Column privilege 1 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Column name            : PROJNO
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : INSERT
+Privilege is grantable : YES
+
+Column privilege 2 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Column name            : PROJNO
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : REFERENCES
+Privilege is grantable : YES
+
+Column privilege 3 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Column name            : PROJNO
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : SELECT
+Privilege is grantable : YES
+
+Column privilege 4 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Column name            : PROJNO
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : UPDATE
+Privilege is grantable : YES
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-columns.html b/python_samples/HTML_Documentation/ibm_db-columns.html new file mode 100644 index 0000000..accf003 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-columns.html @@ -0,0 +1,13525 @@ + + + + +ibm_db-columns + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.columns()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve a list of columns and their associated metadata, for a given table.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.columns( IBM_DBConnectionconnection[, stringqualifierName[, stringschemaName[, stringtableName[, stringcolumnName] ] ] ] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection        : A valid Db2 server or database connection.
  • +
  • qualifierName    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value None or an empty string ('') for Db2 databases on other operating systems.
  • +
  • schemaName     : The name of the schema that contains the table(s) that column information is to be obtained for. To match all schemas, provide the value None or an empty string.
  • +
  • tableName          : The name of the table(s) and/or view(s) that column information is to be obtained for. To match all tables and views, provide the value None or an empty string.
  • +
  • columnName      : The name of the column that information is to be obtained for. To match all columns, provide the value None or an empty string.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an IBM_DBStatement object with a result set that contains the following information:

    +
      +
    • TABLE_CAT                     : The name of the catalog associated with the schema and table the column is in; Db2 does not use catalogs so this field will always contain the value None. (Db2 databases on OS/390 or z/OS servers can return information in this field.)
    • +
    • TABLE_SCHEM                 : The name of the schema for the table or view the column is associated with.
    • +
    • TABLE_NAME                   : The name of the table or view the column is associated with.
    • +
    • COLUMN_NAME                 : The name of the column.
    • +
    • DATA_TYPE                     : An integer value that represents the SQL data type of the column. (On Linux and UNIX systems, valid values for this field can be found in the file /opt/ibm/db2/V11.1/include/sqlcli.h.)
    • +
    • TYPE_NAME                     : The data source-specific string representation of the SQL data type of the column.
    • +
    • COLUMN_SIZE                 : The number of bytes needed to display the column's data as a string.
    • +
    • BUFFER_LENGTH             : The number of bytes needed to store the column's data in an application variable.
    • +
    • DECIMAL_DIGITS           : The scale (i.e., total number of significant digits to the right of the decimal point) of the column - provided the column has a numerical data type. If the column does not have a numerical data type, this field will contain the value None.
    • +
    • NUM_PREC_RADIX           : A numerical value that indicates whether the column's data type represents an exact numeric data type (10) or an approximate numeric data type (2). If the column does not have a numerical data type, this field will contain the value None.
    • +
    • NULLABLE                       : Indication of whether the column accepts a NULL value; ibm_db.SQL_YES will be returned if NULL values are accepted and ibm_db.SQL_NO will be returned if they are not.
    • +
    • REMARKS                         : A user-supplied description of the column (if one has been provided).
    • +
    • COLUMN_DEF                   : The default value for the column (if one has been defined).
    • +
    • SQL_DATA_TYPE             : An integer value that represents the SQL data type of the column, as it would appear in a row descriptor record. In most cases, this will be the same as the value provided in the DATA_TYPE field. (On Linux and UNIX systems, valid values for this field can be found in the file /opt/ibm/db2/V11.1/include/sqlcli.h.)
    • +
    • SQL_DATETIME_SUB       : An integer value that represents the SQL date/time subtype code for the column - provided the column has a date, time, or timestamp data type. If the column does not have one of these data types, this field will contain the value None. (On Linux and UNIX systems, valid values for this field can be found in the file /opt/ibm/db2/V11.1/include/sqlcli.h.)
    • +
    • CHAR_OCTECT_LENGTH   : The length, in octets (8-bit bytes), needed to display the column's data as a string. (This will be the same as the COLUMN_SIZE value for single-byte character set data.) If the column does not have a character data type, this field will contain the value None.
    • +
    • ORDINAL_POSITION       : The column's ordinal position in the table, starting from 1.
    • +
    • IS_NULLABLE                 : Indication of whether the column can contain NULL values, according to the rules in the ISO SQL92 standard. This field will contain the value "YES" if the column can contain NULL values and the value "NO" if it cannot.

    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.columns() API is used to retrieve a list of columns and their associated metadata, for one or more tables and/or views.

+

The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-columns.py                                                                 #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.columns()            #
+#            API.                                                                              #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.fetch_assoc()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+tableName = "ACT"
+resultSet = False
+dataRecord = False
+sqlDataTypes = {0 : "SQL_UNKNOWN_TYPE", 1 : "SQL_CHAR", 2 : "SQL_NUMERIC", 3 : "SQL_DECIMAL",
+    4 : "SQL_INTEGER", 5 : "SQL_SMALLINT", 6 : "SQL_FLOAT", 7 : "SQL_REAL", 8 : "SQL_DOUBLE",
+    9 : "SQL_DATETIME", 12 : "SQL_VARCHAR", 16 : "SQL_BOOLEAN", 19 : "SQL_ROW", 
+    91 : "SQL_TYPE_DATE", 92 : "SQL_TYPE_TIME", 93 : "SQL_TYPE_TIMESTAMP",
+    95 : "SQL_TYPE_TIMESTAMP_WITH_TIMEZONE", -8 : "SQL_WCHAR", -9 : "SQL_WVARCHAR",
+    -10 : "SQL_WLONGVARCHAR", -95 : "SQL_GRAPHIC", -96 : "SQL_VARGRAPHIC",
+    -97 : "SQL_LONGVARGRAPHIC", -98 : "SQL_BLOB", -99 : "SQL_CLOB", -350 : "SQL_DBCLOB",
+    -360 : "SQL_DECFLOAT", -370 : "SQL_XML", -380 : "SQL_CURSORHANDLE", -400 : "SQL_DATALINK",
+    -450 : "SQL_USER_DEFINED_TYPE"}
+sqlDateTimeSubtypes = {1 : "SQL_CODE_DATE", 2 : "SQL_CODE_TIME", 3 : "SQL_CODE_TIMESTAMP",
+    4 : "SQL_CODE_TIMESTAMP_WITH_TIMEZONE"}
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Retrieve Information About All Of The Columns That Have Been Defined For
+# A Particular Table
+print("Obtaining information about columns that have been defined for the ", end="")
+print(tableName + " table ... ", end="")
+try:
+    resultSet = ibm_db.columns(dbConnection, None, None, tableName, None)
+except Exception:
+    pass
+
+# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit
+if resultSet is False:
+    print("\nERROR: Unable to obtain the information desired\n.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# As Long As There Are Records (That Were Produced By The ibm_db.columns API), ...
+noData = False
+loopCounter = 1
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop  
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Information Retrieved
+    else:
+
+        # Display Record Header Information
+        print("Column " + str(loopCounter) + " details:")
+        print("_________________________________________")
+
+        # Display The Information Stored In The Data Record Retrieved
+        print("Table schema             : {}" .format(dataRecord['TABLE_SCHEM']))
+        print("Table name               : {}" .format(dataRecord['TABLE_NAME']))
+        print("Column name              : {}" .format(dataRecord['COLUMN_NAME']))
+        print("Data type                : {}" .format(dataRecord['TYPE_NAME']))
+        print("Size                     : {}" .format(dataRecord['COLUMN_SIZE']))
+        print("Buffer size              : {}" .format(dataRecord['BUFFER_LENGTH']))
+        print("Scale (decimal digits)   : ", end="")
+        if dataRecord['DECIMAL_DIGITS'] == None:
+            print("Not applicable")
+        else:
+            print("{}" .format(dataRecord['DECIMAL_DIGITS']))
+        print("Precision radix          : ", end="")
+        if dataRecord['NUM_PREC_RADIX'] == 10:
+            print("Exact numeric data type")
+        elif dataRecord['NUM_PREC_RADIX'] == 2:
+            print("Approximate numeric data type")
+        elif dataRecord['NUM_PREC_RADIX'] == None:
+            print("Not applicable")
+        print("Can accept NULL values   : ", end="")
+        if dataRecord['NULLABLE'] == ibm_db.SQL_FALSE:
+            print("NO")
+        elif dataRecord['NULLABLE'] == ibm_db.SQL_TRUE:
+            print("YES")
+        print("Remarks                  : {}" .format(dataRecord['REMARKS']))
+        print("Default value            : {}" .format(dataRecord['COLUMN_DEF']))
+        print("SQL data type            : ", end="")
+        print(sqlDataTypes.get(dataRecord['SQL_DATA_TYPE']))
+        print("SQL data/time subtype    : ", end="")
+        print(sqlDateTimeSubtypes.get(dataRecord['SQL_DATETIME_SUB']))
+        print("Data type                : {}" .format(dataRecord['DATA_TYPE']))
+        print("Length in octets         : ", end="")
+        if dataRecord['CHAR_OCTET_LENGTH'] == None:
+            print("Not applicable")
+        else:
+            print("{}" .format(dataRecord['CHAR_OCTET_LENGTH']))
+        print("Ordinal position         : {}" .format(dataRecord['ORDINAL_POSITION']))
+        print("Can contain NULL values  : {}" .format(dataRecord['IS_NULLABLE']))
+
+        # Increment The loopCounter Variable And Print A Blank Line To Separate The
+        # Records From Each Other
+        loopCounter += 1
+        print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Obtaining information about columns that have been defined for the ACT table ... Done!
+
+Column 1 details:
+_________________________________________
+Table schema             : DB2INST1
+Table name               : ACT
+Column name              : ACTNO
+Data type                : SMALLINT
+Size                     : 5
+Buffer size              : 2
+Scale (decimal digits)   : 0
+Precision radix          : Exact numeric data type
+Can accept NULL values   : NO
+Remarks                  : None
+Default value            : None
+SQL data type            : SQL_SMALLINT
+SQL data/time subtype    : None
+Data type                : 5
+Length in octets         : Not applicable
+Ordinal position         : 1
+Can contain NULL values  : NO
+
+Column 2 details:
+_________________________________________
+Table schema             : DB2INST1
+Table name               : ACT
+Column name              : ACTKWD
+Data type                : CHAR
+Size                     : 6
+Buffer size              : 6
+Scale (decimal digits)   : Not applicable
+Precision radix          : Not applicable
+Can accept NULL values   : NO
+Remarks                  : None
+Default value            : None
+SQL data type            : SQL_CHAR
+SQL data/time subtype    : None
+Data type                : 1
+Length in octets         : 6
+Ordinal position         : 2
+Can contain NULL values  : NO
+
+Column 3 details:
+_________________________________________
+Table schema             : DB2INST1
+Table name               : ACT
+Column name              : ACTDESC
+Data type                : VARCHAR
+Size                     : 20
+Buffer size              : 20
+Scale (decimal digits)   : Not applicable
+Precision radix          : Not applicable
+Can accept NULL values   : NO
+Remarks                  : None
+Default value            : None
+SQL data type            : SQL_VARCHAR
+SQL data/time subtype    : None
+Data type                : 12
+Length in octets         : 20
+Ordinal position         : 3
+Can contain NULL values  : NO
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-commit.html b/python_samples/HTML_Documentation/ibm_db-commit.html new file mode 100644 index 0000000..7c6f2e2 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-commit.html @@ -0,0 +1,13434 @@ + + + + +ibm_db-commit + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.commit()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Terminate an in-progress transaction and make the effects of all operations performed within the transaction permanent.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.commit( IBM_DBConnectionconnection)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server or database connection.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • True      : Changes made by the current transaction were made permanent (committed).
  • +
  • False    : Changes made by the current transaction were not committed.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.commit() API is used to terminate an in-progress transaction and apply all changes that were made by that transaction to the database. (A transaction is a sequence of one or more SQL operations that are grouped together as a single process; when a transaction is committed, the effects of all operations that were performed by the transaction are made permanent.) Normally, a transaction is initiated the first time an SQL statement is executed after a database connection is established or an in-progress transaction ends. But, with Python applications, each SQL operation is treated as a transaction that is implicitly committed as soon as it completes unless AUTOCOMMIT behavior is turned OFF. Consequently, the ibm_db.commit() API has no effect when AUTOCOMMIT behavior is ON (the default).

+

It is important to note that if the connection being used is a persistent connection (i.e., a connection that was established with the ibm_db.pconnect() API), in-progress transactions for all applications using the connection will be rolled back when this API is called. For this reason, the use of persistent connections is not recommended for applications that need to control transaction boundaries.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-commit.py                                                                  #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.commit() API.        #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.autocommit()                                                          #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.stmt_errormsg()                                                       #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The get_row_count() Function That Has Been Defined In The File Named                  #
+# "ibm_db_tools.py";  This Function Contains The Programming Logic Needed To Obtain And        #
+# Display The Number Of Rows (Records) Found In A Db2 Database Table                           #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import get_row_count
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+returnCode = False
+resultSet = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Turn Autocommit Behavior OFF
+print("Turning AUTOCOMMIT behavior OFF ... ", end="")
+try:
+    returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_OFF)
+except Exception:
+    pass
+
+# If AUTOCOMMIT Behavior Could Not Be Turned OFF, Display An Error Message And Continue
+if returnCode is False:
+    print("\nERROR: Unable to turn AUTOCOMMIT behavior OFF.")
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table
+returnCode = get_row_count(dbConnection, 'DEPARTMENT')
+if returnCode is False:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The INSERT Statement That Is To Be Used To Add Data To The DEPARTMENT Table
+sqlStatement = "INSERT INTO department VALUES('K01', 'SALES', '000130', 'K01', NULL)"
+
+# Execute The SQL Statement Just Defined
+print("Inserting a record into the DEPARTMENT table ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the INSERT statement specified.")
+    errorMsg = ibm_db.stmt_errormsg()
+    print("\n" + errorMsg + "\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display The Number Of Rows That Exist In The DEPARTMENT Table Now
+# (The Number Returned Should Change)
+returnCode = get_row_count(dbConnection, 'DEPARTMENT')
+if returnCode is False:
+    conn.closeConnection()
+    exit(-1)
+
+# Commit The Changes Just Made (To Make Them Permanent)
+print("Commiting changes made to the database ... ", end="")
+resultSet = False
+try:
+    resultSet = ibm_db.commit(dbConnection)
+except Exception:
+    pass
+
+# If The Commit Operation Could Not Be Performed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to commit the previous operation.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display The Number Of Rows That Exist In The DEPARTMENT Table Now
+# (The Number Should Not Change)
+returnCode = get_row_count(dbConnection, 'DEPARTMENT')
+if returnCode is False:
+    conn.closeConnection()
+    exit(-1)
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Turning AUTOCOMMIT behavior OFF ... Done!
+
+Number of records found in the DEPARTMENT table: 14
+
+Inserting a record into the DEPARTMENT table ... Done!
+
+Number of records found in the DEPARTMENT table: 15
+
+Commiting changes made to the database ... Done!
+
+Number of records found in the DEPARTMENT table: 15
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-conn_error.html b/python_samples/HTML_Documentation/ibm_db-conn_error.html new file mode 100644 index 0000000..4a8a2e0 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-conn_error.html @@ -0,0 +1,13396 @@ + + + + +ibm_db-conn_error + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.conn_error()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Return an SQLSTATE value associated with an IBM_DBConnection object.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

string ibm_db.conn_error( [ IBM_DBConnectionconnection] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server or database connection.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+

When a connection value is provided:

+
    +
  • If there is an error associated with the Db2 server or database connection specified, a string containing an SQLSTATE value that explains why the last operation using the IBM_DBConnection object failed.
  • +
  • If there is no error associated with the Db2 server or database connection specified, an empty string ('').
  • +
+ +
+
+
+
+
+
+

When a connection value is not provided:

+
    +
  • If there is an error associated with the last attempt to return an IBM_DBConnection object from an ibm_db.connect() or ibm_db.pconnect API, a string containing an SQLSTATE value that explains why the API failed.
  • +
  • If there is no error associated with the last attempt to return an IBM_DBConnection object, an empty string ('').
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.conn_error() API can be used to return an SQLSTATE value that explains why an attempt to establish a Db2 server or database connection (using the ibm_db.connect() or ibm_db.pconnect() API) was not successful. It can also be used to return an SQLSTATE value that identifies why the last operation using a IBM_DBConnection object failed.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-conn_error.py                                                              #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.conn_error() API.    #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.connect()                                                             #
+#                 ibm_db.close()                                                               #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw_rd"        # The Wrong Password Is Used To Force An Error To Occur
+dbConnection = None
+
+# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database
+# Is About To Be Made
+print("\nConnecting to the \'" + dbName + "\' database ... ", end="")
+
+# Construct The String That Will Be Used To Establish A Db2 Database Connection
+connString = "ATTACH=FALSE"              # Attach To A Database; Not A Server
+connString += ";DATABASE=" + dbName      # Required To Connect To A Database     
+connString += ";PROTOCOL=TCPIP"
+connString += ";UID=" + userID
+connString += ";PWD=" + passWord
+
+# Attempt To Establish A Connection To The Database Specified
+try:
+    dbConnection = ibm_db.connect(connString, '', '')
+except Exception:
+    pass
+
+# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit
+if dbConnection is None:
+    print("\nERROR: Unable to connect to the \'" + dbName + "\' database.")
+    errorCode = ibm_db.conn_error()
+    print("\nSQLSTATE: "+ errorCode + "\n")
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+
+# Add Additional Db2 Database-Related Processing Here ...
+
+
+# Attempt To Close The Db2 Database Connection That Was Just Opened
+if not dbConnection is None:
+    print("Disconnecting from the \'" + dbName + "\' database ... ", end="")
+    try:
+        returnCode = ibm_db.close(dbConnection)
+    except Exception:
+        pass
+
+    # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit
+    if returnCode is False:
+        print("\nERROR: Unable to disconnect from the " + dbName + " database.")
+        errorCode = ibm_db.conn_error(dbConnection)
+        print("SQLSTATE: "+ errorCode + "\n")
+        exit(-1)
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!\n")
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the 'SAMPLE' database ... 
+ERROR: Unable to connect to the 'SAMPLE' database.
+
+SQLSTATE: 08001
+
+
+
+
+ +
+ +
+ + +
+
+An exception has occurred, use %tb to see the full traceback.
+
+ipynb_Exit
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-conn_errormsg.html b/python_samples/HTML_Documentation/ibm_db-conn_errormsg.html new file mode 100644 index 0000000..9286675 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-conn_errormsg.html @@ -0,0 +1,13396 @@ + + + + +ibm_db-conn_errormsg + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.conn_errormsg()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Return an SQLCODE and corresponding error message associated with an IBM_DBConnection object.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

string ibm_db.conn_errormsg( [ IBM_DBConnectionconnection] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server or database connection.
  • +
+ +
+
+
+
+
+
+

Return codes:

+
+
+
+
+
+
+

When a connection value is provided:

+
    +
  • If there is an error associated with the Db2 server or database connection specified, a string containing an SQLCODE and corresponding error message that explains why the last operation using the IBM_DBConnection object failed.
  • +
  • If there is no error associated with the Db2 server or database connection specified, an empty string ('').
  • +
+ +
+
+
+
+
+
+

When a connection value is not provided:

+
    +
  • If there is an error associated with the last attempt to return an IBM_DBConnection object from an ibm_db.connect() or ibm_db.pconnect API, a string containing an SQLCODE and corresponding error message that explains why the API failed.
  • +
  • If there is no error associated with the last attempt to return an IBM_DBConnection object, an empty string ('').
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.conn_errormsg() API can be used to return an SQLCODE and corresponding error message that explains why an attempt to establish a Db2 server or database connection (using the ibm_db.connect() or ibm_db.pconnect() API) was not successful. It can also be used to return an SQLCODE and error message that identifies why the last operation using a IBM_DBConnection object failed.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-conn_errormsg.py                                                           #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.conn_errormsg() API. #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.connect()                                                             #
+#                 ibm_db.close()                                                               #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw_rd"        # The Wrong Password Is Used To Force An Error To Occur
+dbConnection = None
+
+# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database
+# Is About To Be Made
+print("\nConnecting to the \'" + dbName + "\' database ... ", end="")
+
+# Construct The String That Will Be Used To Establish A Db2 Database Connection
+connString = "ATTACH=FALSE"              # Attach To A Database; Not A Server
+connString += ";DATABASE=" + dbName      # Required To Connect To A Database     
+connString += ";PROTOCOL=TCPIP"
+connString += ";UID=" + userID
+connString += ";PWD=" + passWord
+
+# Attempt To Establish A Connection To The Database Specified
+try:
+    dbConnection = ibm_db.connect(connString, '', '')
+except Exception:
+    pass
+
+# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit
+if dbConnection is None:
+    print("\nERROR: Unable to connect to the \'" + dbName + "\' database.")
+    errorMsg = ibm_db.conn_errormsg()
+    print("\n" + errorMsg + "\n")
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+
+# Add Additional Db2 Database-Related Processing Here ...
+
+
+# Attempt To Close The Db2 Database Connection That Was Just Opened
+if not dbConnection is None:
+    print("Disconnecting from the \'" + dbName + "\' database ... ", end="")
+    try:
+        returnCode = ibm_db.close(dbConnection)
+    except Exception:
+        pass
+
+    # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit
+    if returnCode is False:
+        print("\nERROR: Unable to disconnect from the " + dbName + " database.")
+        errorCode = ibm_db.conn_error(dbConnection)
+        print("SQLSTATE: "+ errorCode + "\n")
+        exit(-1)
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!\n")
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the 'SAMPLE' database ... 
+ERROR: Unable to connect to the 'SAMPLE' database.
+
+[IBM][CLI Driver] SQL30082N  Security processing failed with reason "24" ("USERNAME AND/OR PASSWORD INVALID").  SQLSTATE=08001 SQLCODE=-30082
+
+
+
+
+ +
+ +
+ + +
+
+An exception has occurred, use %tb to see the full traceback.
+
+ipynb_Exit
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-connect.html b/python_samples/HTML_Documentation/ibm_db-connect.html new file mode 100644 index 0000000..6122670 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-connect.html @@ -0,0 +1,13571 @@ + + + + +ibm_db-connect + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.connect()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Establish a new connection to an IBM Db2 server or database.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBConnection ibm_db.connect( stringconnectionInfo,stringuserID,stringuserPassword[, dictionaryoptions[, constantreplaceQuotedLiterals] ] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connectionInfo                : A valid Db2 database alias (if the database has been cataloged in the system database directory) or a connection string with the format DRIVER={IBM DB2 ODBC DRIVER};ATTACH=connType;DATABASE=dbName;HOSTNAME=hostName;PORT=port;PROTOCOL=TCPIP;UID=userName;PWD=password where:

    +
      +
    • connType     : Specifies whether the connection is to be made to a Db2 server or database; TRUE indicates the connection is to be made to a Db2 server and FALSE indicates the connection is to be made to a database.
    • +
    • dbName         : The name of the Db2 server or database the connection is to be made to. This option is only required when connecting to a Db2 database.
    • +
    • hostName     : The host name or IP address of the Db2 server the connection is to be made to. (The hostname is the name of the Db2 server, as it is known to the TCP/IP network.) This option is only required when connecting to a Db2 server.
    • +
    • port             : The port number that receives Db2 connections on the server the connection is to be made to. (Port number 50000 is used by default.) This option is only required when connecting to a Db2 server.
    • +
    • userName     : The user name/ID that is to be used for authentication when the connection is established.
    • +
    • password     : The password that corresponds to the user name/ID specified in the userName parameter.

    • +
    +
  • +
  • userID                               : The user ID that is to be used for authentication when a connection is established. If a Db2 database alias is NOT provided in the connectionInfo parameter, this parameter must contain an empty string.

    +
  • +
  • userPassword                  : The password that corresponds to the user ID specified in the userPassword parameter. If a Db2 database alias is NOT provided in the connectionInfo parameter, this parameter must contain an empty string.
  • +
  • options                             : A dictionary containing key-value pairs for the attributes that are to be set before a connection is established. Valid keys for IBM_DBConnection objects are:

    +
      +
    • ibm_db.SQL_ATTR_AUTOCOMMIT                     : Specifies whether AUTOCOMMIT mode is to be used or not; ibm_db.SQL_AUTOCOMMIT_ON will turn AUTOCOMMIT behavior ON and ibm_db.SQL_AUTOCOMMIT_OFF will turn it OFF.
    • +
    • ibm_db.SQL_ATTR_CASE                                 : The case that column names will be returned in; ibm_db.CASE_NATURAL will cause column names to be returned in natural case, ibm_db.CASE_LOWER will cause them to be returned in lower case, and ibm_db.CASE_UPPER will cause them to be returned in upper case. (This attribute can only be used with Db2 databases on OS/390 or z/OS servers.)
    • +
    • ibm_db.SQL_ATTR_CURRENT_SCHEMA             : The name of the schema to use, by default, when performing operations that require a schema name and one is not provided.
    • +
    • ibm_db.SQL_ATTR_USE_TRUSTED_CONTEXT   : Specifies whether the connection to a Db2 server or database is to be treated as a trusted connection; ibm_db.SQL_TRUE indicates the connection can be trusted and ibm_db.SQL_FALSE indicates the connection should not to be treated as a trusted connection.

    • +
    +
  • +
  • replaceQuotedLiterals    : Identifies whether quotes are allowed around literal values. Valid values for this parameter are:

    +
      +
    • ibm_db.QUOTED_LITERAL_REPLACEMENT_ON     : Quotes cannot be used with literal values. For example, if the SQL statement SELECT deptname FROM org WHERE deptnumb = '50000' is executed and the deptnumb column has a numeric data type, an error will occur. (This is the default behavior.)
    • +
    • ibm_db.QUOTED_LITERAL_REPLACEMENT_OFF   : Quotes can be used with literal values. For example, if the SQL statement SELECT deptname FROM org WHERE deptnumb = '50000' is executed and the deptnumb column has a numeric data type, the data requested will be returned.
    • +
    +
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, a valid IBM_DBConnection object.
  • +
  • If unsuccessful, the value None.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.connect() API is used to establish a new connection to an IBM Db2 server or database.

+

If a connection to a remote Db2 server or database is desired, the information needed to connect to the server (i.e., the host name, port number, and communications protocol) must be provided before a connection to either resource can be established. If a connection to a local, cataloged Db2 database is needed instead, just the alias for the database, as defined in the system database directory, must be supplied; values for the userID and userPassword parameters are optional. (If this API is called and just a local database alias is provided — for example, conn = ibm_db.connect( 'SAMPLE', ' ', ' ' ), — an attempt to establish a connection to the database will be made using the authorization ID and password for the current logged in Db2 instance user.)

+ +
+
+
+
+
+
+

Examples:

+
+
+
+
+
+
+

  Example 1: Connect to a local, cataloged Db2 database

+ +
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-connect_DB.py                                                              #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.connect() API to     #
+#            establish a connection to a local Db2 database.                                   #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.close()                                                               #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"        # The Alias For The Cataloged, Local Database
+userID = "db2inst1"      # The Instance User ID At The Local Server
+passWord = "Passw0rd"    # The Password For The Instance User ID At The Local Server
+connOption = {ibm_db.SQL_ATTR_AUTOCOMMIT: ibm_db.SQL_AUTOCOMMIT_ON}
+connectionID = None
+resultSet = False
+
+# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database
+# Is About To Be Made
+print("\nConnecting to the \'" + dbName + "\' database ... ", end="")
+
+# Construct The String That Will Be Used To Establish A Db2 Database Connection
+connString = "ATTACH=FALSE"              # Attach To A Database; Not A Server
+connString += ";DATABASE=" + dbName      # Required To Connect To A Database     
+connString += ";PROTOCOL=TCPIP"
+connString += ";UID=" + userID
+connString += ";PWD=" + passWord
+
+# Attempt To Establish A Connection To The Database Specified
+try:
+    connectionID = ibm_db.connect(connString, '', '', connOption, 
+        ibm_db.QUOTED_LITERAL_REPLACEMENT_OFF)
+except Exception:
+    pass
+
+# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit
+if connectionID is None:
+    print("\nERROR: Unable to connect to the \'" + dbName + "\' database.")
+    print("Connection string used: " + connString + "\n")
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+    
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT deptname FROM org WHERE deptnumb = '50000'"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(connectionID, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    if not connectionID is None:
+        ibm_db.close(connectionID)
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n") 
+    
+# Attempt To Close The Db2 Database Connection That Was Opened Earlier
+if not connectionID is None:
+    print("Disconnecting from the \'" + dbName + "\' database ... ", end="")
+    try:
+        returnCode = ibm_db.close(connectionID)
+    except Exception:
+        pass
+
+    # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit
+    if returnCode is False:
+        print("\nERROR: Unable to disconnect from the " + dbName + " database.")
+        exit(-1)
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!\n")
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the 'SAMPLE' database ... Done!
+
+Executing the SQL statement "SELECT deptname FROM org WHERE deptnumb = '50000'" ... Done!
+
+Disconnecting from the 'SAMPLE' database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
+

  Example 2: Connect to a remote Db2 server

+ +
+
+
+
+
+
In [2]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-connect_SERVER.py                                                          #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.connect() API to     #
+#            establish a connection to a remote Db2 server.                                    #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.close()                                                               #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+hostName = "197.126.80.22"    # IP Address Of Remote Server
+portNum = "50000"             # Port Number That Receives Db2 Connections On The Remote Server 
+userID = "db2inst2"           # The Instance User ID At The Remote Server
+passWord = "ibmdb2"           # The Password For The Instance User ID At The Remote Server
+connectionID = None
+
+# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Server
+# Is About To Be Made
+print("\nConnecting to the \'" + hostName + "\' server ... ", end="")
+            
+# Construct The String That Will Be Used To Establish A Db2 Server Connection
+connString = "DRIVER={IBM DB2 ODBC DRIVER}"
+connString += ";ATTACH=TRUE"             # Attach To A Server; Not A Database
+connString += ";DATABASE="               # Ignored When Connecting To A Server
+connString += ";HOSTNAME=" + hostName    # Required To Connect To A Server
+connString += ";PORT=" + portNum         # Required To Connect To A Server
+connString += ";PROTOCOL=TCPIP"          # Required To Connect To A Server
+connString += ";UID=" + userID
+connString += ";PWD=" + passWord
+
+# Attempt To Establish A Connection To The Server Specified
+try:
+    connectionID = ibm_db.connect(connString, '', '')
+except Exception:
+    pass
+
+# If A Db2 Server Connection Could Not Be Established, Display An Error Message And Exit
+if connectionID is None:
+    print("\nERROR: Unable to connect to the \'" + hostName + "\' server.")
+    print("Connection string used: " + connString + "\n")
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+
+# Add Additional Db2 Server-Related Processing Here ...
+# For Example, ibm_db.createdb(), ibm_db.createdbNX(), ibm_db.recreatedb(), ibm_db.dropdb()
+
+
+# Attempt To Close The Db2 Server Connection That Was Just Opened
+if not connectionID is None:
+    print("Disconnecting from the \'" + hostName + "\' server ... ", end="")
+    try:
+        returnCode = ibm_db.close(connectionID)
+    except Exception:
+        pass
+
+    # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit
+    if returnCode is False:
+        print("\nERROR: Unable to disconnect from the " + hostName + " server.")
+        exit(-1)
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!\n")
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the '197.126.80.22' server ... Done!
+
+Disconnecting from the '197.126.80.22' server ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-createdb.html b/python_samples/HTML_Documentation/ibm_db-createdb.html new file mode 100644 index 0000000..4e9aaa7 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-createdb.html @@ -0,0 +1,13510 @@ + + + + +ibm_db-createdb + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.createdb()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Create a new database using the name and code set specified.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.createdb( IBM_DBConnectionconnection, stringdbName[, stringcodeSet] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server connection.
  • +
  • dbName         : The name to assign to the database that is to be created.
  • +
  • codeSet         : The code set that is to be used for storing data that is entered into the database. If a codeSet value is not specified, the UTF-8 (Unicode) code set is used.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • True      : The database specified was created.
  • +
  • False    : The database specified could not be created.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.createdb() API is used to create a new database and assign it the name specified. Optionally, the code set that is to be used for storing data entered into the database can also be specified when this API is executed. (The code set controls how unique numbers are assigned to characters in a particular character set.)

+

It's important to note that when this API is used, the name that is to be assigned to the database being created must be unique from all other database names in the system database or local database directory. If the name provided is the same as that of a database that already exists, an error will be generated and the database will not be created. This is different from when the ibm_db.createdbNX() API is used to create a database and the name specified matches the name of a database that already exists.

+ +
+
+
+
+
+
+

Examples:

+
+
+
+
+
+
+

  Example 1: Create a new database at a local server

+ +
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-createdb_LOCAL.py                                                          #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.createdb() API to    #
+#            create a local Db2 database.                                                      #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.conn_errormsg()                                                       #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+userID = "db2inst1"           # User ID (Recognized By The Local Server)
+passWord = "Passw0rd"         # User Password
+svrConnection = None
+dbName = "MY_DB"
+returnCode = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To The Local Db2 Server
+conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    svrConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Create A New Database At The Local Server
+print("Creating a database named " + dbName + " at the local server. Please wait.")
+try:
+    returnCode = ibm_db.createdb(svrConnection, dbName)
+except Exception:
+    pass
+
+# If The Database Could Not Be Created, Display An Error Message And Exit 
+if returnCode is False:
+    print("ERROR: Unable to create the " + dbName + " database.\n")
+    errorMsg = ibm_db.conn_errormsg(svrConnection)
+    print(errorMsg + "\n")
+    conn.closeConnection()
+    exit(-1)
+    
+# Otherwise, Display A Status Message 
+else:
+    print("\nThe database \"" + dbName + "\" has been created!\n")
+
+# Close The Db2 Server Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the local server ... Done!
+
+Creating a database named MY_DB at the local server. Please wait.
+
+The database "MY_DB" has been created!
+
+Disconnecting from the local server ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
+

  Example 2: Create a new database at a remote server

+ +
+
+
+
+
+
In [2]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-createdb_REMOTE.py                                                         #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.createdb() API to    #
+#            create a database on a remote Db2 server.                                         #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.conn_errormsg()                                                       #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+hostName = "197.126.80.22"    # IP Address Of A Remote Server
+portNum = "50000"             # Port Number Used By Db2
+userID = "db2inst2"           # User ID (Recognized By The Remote Server)
+passWord = "ibmdb2"           # User Password
+svrConnection = None
+dbName = "MY_DB"
+returnCode = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server
+conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    svrConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Create A New Database At The Remote Server
+print("Creating a database named " + dbName + " at the " + hostName + " server. Please wait.")
+try:
+    returnCode = ibm_db.createdb(svrConnection, dbName)
+except Exception:
+    pass
+
+# If The Database Could Not Be Created, Display An Error Message And Exit 
+if returnCode is False:
+    print("ERROR: Unable to create the " + dbName + " database.\n")
+    errorMsg = ibm_db.conn_errormsg(svrConnection)
+    print(errorMsg + "\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Display A Status Message Indicating The Database Was Created And Close The
+# Db2 Server Connection That Was Opened Earlier
+else:
+    print("\nThe database \"" + dbName + "\" has been created!\n")
+    conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the 197.126.80.22 server ... Done!
+
+Creating a database named MY_DB at the 197.126.80.22 server. Please wait.
+
+The database "MY_DB" has been created!
+
+Disconnecting from the 197.126.80.22 server ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-createdbNX.html b/python_samples/HTML_Documentation/ibm_db-createdbNX.html new file mode 100644 index 0000000..6219bc0 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-createdbNX.html @@ -0,0 +1,13510 @@ + + + + +ibm_db-createdbNX + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.createdbNX()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Create a new database using the name and code set specified; if the datebase already exists, do not return an error.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.createdbNX ( IBM_DBConnectionconnection, stringdbName[, stringcodeSet] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server connection.
  • +
  • dbName         : The name to assign to the database that is to be created.
  • +
  • codeSet         : The code set that is to be used for storing data that is entered into the database. If a codeSet value is not specified, the UTF-8 (Unicode) code set is used.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • True      : The database specified already exists or was successfully created.
  • +
  • False    : The database specified could not be created.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.createdbNX() API is used to create a new database and assign it the name specified; the code set that is to be used for storing data entered into the database can also be specified when this API is executed. (The code set controls how unique numbers are assigned to characters in a particular character set.)

+

It's important to note that when this API is used, the name that is to be assigned to the database being created should be unique from all other database names in the system database or local database directory. If the name provided is the same as that of a database that already exists, the database will not be created; however, an error will not be produced. This is different from when the ibm_db.createdb() API is used to create a database and the name specified matches the name of a database that already exists.

+ +
+
+
+
+
+
+

Examples:

+
+
+
+
+
+
+

  Example 1: Create a new database at a local server

+ +
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-createdbNX_LOCAL.py                                                        #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.createdbNX() API     #
+#            to create a local Db2 database.                                                   #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.conn_errormsg()                                                       #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+userID = "db2inst1"           # User ID (Recognized By The Local Server)
+passWord = "Passw0rd"         # User Password
+svrConnection = None
+dbName = "MY_DB"
+returnCode = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To The Local Db2 Server
+conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    svrConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Create A New Database At The Local Server
+print("Creating a database named " + dbName + " at the local server. Please wait.")
+try:
+    returnCode = ibm_db.createdbNX(svrConnection, dbName)
+except Exception:
+    pass
+
+# If The Database Could Not Be Created, Display An Error Message And Exit 
+if returnCode is False:
+    print("ERROR: Unable to create the " + dbName + " database.\n")
+    errorMsg = ibm_db.conn_errormsg(svrConnection)
+    print(errorMsg + "\n")
+    conn.closeConnection()
+    exit(-1)
+    
+# Otherwise, Display A Status Message 
+else:
+    print("\nThe database \"" + dbName + "\" has been created!\n")
+
+# Close The Db2 Server Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the local server ... Done!
+
+Creating a database named MY_DB at the local server. Please wait.
+
+The database "MY_DB" has been created!
+
+Disconnecting from the local server ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
+

  Example 2: Create a new database at a remote server

+ +
+
+
+
+
+
In [2]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-createdbNX_REMOTE.py                                                       #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.createdbNX() API     #
+#            to create a database on a remote Db2 server.                                      #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.conn_errormsg()                                                       #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+hostName = "197.126.80.22"    # IP Address Of A Remote Server
+portNum = "50000"             # Port Number Used By Db2
+userID = "db2inst2"           # User ID (Recognized By The Remote Server)
+passWord = "ibmdb2"           # User Password
+svrConnection = None
+dbName = "MY_DB"
+returnCode = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server
+conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    svrConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Create A New Database At The Remote Server
+print("Creating a database named " + dbName + " at the " + hostName + " server. Please wait.")
+try:
+    returnCode = ibm_db.createdbNX(svrConnection, dbName)
+except Exception:
+    pass
+
+# If The Database Could Not Be Created, Display An Error Message And Exit 
+if returnCode is False:
+    print("ERROR: Unable to create the " + dbName + " database.\n")
+    errorMsg = ibm_db.conn_errormsg(svrConnection)
+    print(errorMsg + "\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Display A Status Message Indicating The Database Was Created And Close The
+# Db2 Server Connection That Was Opened Earlier
+else:
+    print("\nThe database \"" + dbName + "\" has been created!\n")
+    conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the 197.126.80.22 server ... Done!
+
+Creating a database named MY_DB at the 197.126.80.22 server. Please wait.
+
+The database "MY_DB" has been created!
+
+Disconnecting from the 197.126.80.22 server ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-cursor_type.html b/python_samples/HTML_Documentation/ibm_db-cursor_type.html new file mode 100644 index 0000000..01329da --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-cursor_type.html @@ -0,0 +1,13462 @@ + + + + +ibm_db-cursor_type + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.cursor_type()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve information about the type of cursor currently being used.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

int ibm_db.cursor_type( IBM_DBStatementstatement)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object.
  • +
+ +
+
+
+
+
+
+

Return Values:

+
+
+
+
+
+
+
    +
  • If successful, one of the following values:

    +
      +
    • 0 or ibm_db.SQL_CURSOR_FORWARD_ONLY          : A forward only cursor is being used.
    • +
    • 1 or ibm_db. SQL_CURSOR_KEYSET_DRIVEN      : A keyset-driven cursor is being used.
    • +
    • 2 or ibm_db.SQL_CURSOR_DYNAMIC                    : A dynamic, scrollable cursor is being used. Dynamic cursors are only supported by Db2 for z/OS servers.
    • +
    • 3 or ibm_db.SQL_CURSOR_STATIC                      : A static cursor is being used.
    • +
    +
  • +
+
    +
  • If unsuccessful, a Python interpreter error.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.cursor_type() API is used to retrieve information about the type of cursor currently being used. This API can be used in place of the ibm_db.get_option() API to determine if you are working with a forward-only cursor or a scrollable cursor.

+

It's important to note that if a cursor type that is not supported was specified with the ibm_db.prepare(), ibm_db.exec_immediate(), or ibm_db.set_option() API, that cursor type is substituteed with a different cursor type; for a mixed or dynamic cursor, ibm_db substitutes, in order, a keyset-driven cursor or a static cursor.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-cursor_type.py                                                             #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.cursor_type() API    #
+#            to determine the type of cursor being used.                                       #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.set_option()                                                          #
+#                 ibm_db.exec_immediate()                                                      #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+cursorType = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT * FROM department"
+
+# Create A Dictionary That Contains The Value Needed To Specify That A Forward Only Cursor
+# Should Be Used
+print("Setting cursor type to SQL_CURSOR_FORWARD_ONLY\n")
+stmtOption = {ibm_db.SQL_ATTR_CURSOR_TYPE: ibm_db.SQL_CURSOR_FORWARD_ONLY}
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement, stmtOption)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified
+print("Obtaining information about the type of cursor being used ... ", end="")
+try:
+    cursorType = ibm_db.cursor_type(resultSet)
+except Exception:
+    pass
+
+# If Information About The Cursor Could Not Be Obtained, Display An Error Message And Exit 
+if cursorType is False:
+    print("\nERROR: Unable to obtain the information desired.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified
+print("Type of cursor being used: ", end="")
+
+if cursorType == ibm_db.SQL_CURSOR_FORWARD_ONLY:
+    print("Forward only (SQL_CURSOR_FORWARD_ONLY)\n")
+elif cursorType == ibm_db.SQL_CURSOR_KEYSET_DRIVEN:
+    print("Keyset driven (SQL_CURSOR_KEYSET_DRIVEN)\n")
+elif cursorType == ibm_db.SQL_CURSOR_DYNAMIC:
+    print("Dynamic (SQL_CURSOR_DYNAMIC)\n")
+elif cursorType == ibm_db.SQL_CURSOR_STATIC:
+    print("Static (SQL_CURSOR_STATIC)\n")
+else:
+    print("Unknown\n")
+
+# Create A Dictionary That Contains The Value Needed To Specify That A Keyset-Driven Cursor
+# Should Be Used
+print("\nSetting cursor type to SQL_CURSOR_KEYSET_DRIVEN\n")
+stmtOption = {ibm_db.SQL_ATTR_CURSOR_TYPE: ibm_db.SQL_CURSOR_KEYSET_DRIVEN}
+
+# Execute The SQL Statement Defined Earlier
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement, stmtOption)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified
+print("Obtaining information about the type of cursor being used ... ", end="")
+try:
+    cursorType = ibm_db.cursor_type(resultSet)
+except Exception:
+    pass
+
+# If Information About The Cursor Could Not Be Obtained, Display An Error Message And Exit 
+if cursorType is False:
+    print("\nERROR: Unable to obtain the information desired.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified
+print("Type of cursor being used: ", end="")
+
+if cursorType == ibm_db.SQL_CURSOR_FORWARD_ONLY:
+    print("Forward only (SQL_CURSOR_FORWARD_ONLY)\n")
+elif cursorType == ibm_db.SQL_CURSOR_KEYSET_DRIVEN:
+    print("Keyset driven (SQL_CURSOR_KEYSET_DRIVEN)\n")
+elif cursorType == ibm_db.SQL_CURSOR_DYNAMIC:
+    print("Dynamic (SQL_CURSOR_DYNAMIC)\n")
+elif cursorType == ibm_db.SQL_CURSOR_STATIC:
+    print("Static (SQL_CURSOR_STATIC)\n")
+else:
+    print("Unknown\n")
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Setting cursor type to SQL_CURSOR_FORWARD_ONLY
+
+Executing the SQL statement "SELECT * FROM department" ... Done!
+
+Obtaining information about the type of cursor being used ... Done!
+
+Type of cursor being used: Forward only (SQL_CURSOR_FORWARD_ONLY)
+
+
+Setting cursor type to SQL_CURSOR_KEYSET_DRIVEN
+
+Executing the SQL statement "SELECT * FROM department" ... Done!
+
+Obtaining information about the type of cursor being used ... Done!
+
+Type of cursor being used: Keyset driven (SQL_CURSOR_KEYSET_DRIVEN)
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-dropdb.html b/python_samples/HTML_Documentation/ibm_db-dropdb.html new file mode 100644 index 0000000..11ca133 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-dropdb.html @@ -0,0 +1,13509 @@ + + + + +ibm_db-dropdb + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.dropdb()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Delete (drop) the database specified.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.dropdb( IBM_DBConnectionconnection,stringdbName)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server connection.
  • +
  • dbName         : The name of the database that is to be deleted (dropped).
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • True      : The database specified was deleted (dropped).
  • +
  • False    : The database specified could not be deleted (dropped).
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.dropdb() API is used to delete (drop) an existing database and remove information about it from both the system database directory and the local database directory.

+ +
+
+
+
+
+
+

Examples:

+
+
+
+
+
+
+

  Example 1: Delete a database stored on a local server

+ +
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-dropdb_LOCAL.py                                                            #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.dropdb() API to      #
+#            delete (drop) a local Db2 database.                                               #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.conn_errormsg()                                                       #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+userID = "db2inst1"           # User ID (Recognized By The Local Server)
+passWord = "Passw0rd"         # User Password
+svrConnection = None
+dbName = "MY_DB"
+returnCode = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Remote Db2 Server
+conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    svrConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Delete (Drop) A Database At The Remote Server
+print("Dropping a database named " + dbName + " at the local server. Please wait.")
+try:
+    returnCode = ibm_db.dropdb(svrConnection, dbName)
+except Exception:
+    pass
+
+# If The Database Could Not Be Deleted, Display An Error Message And Exit 
+if returnCode is False:
+    print("ERROR: Unable to drop the " + dbName + " database.\n")
+    errorMsg = ibm_db.conn_errormsg(svrConnection)
+    print(errorMsg + "\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Display A Status Message And Verify That Information About The Database
+# That Was Just Deleted No Longer Exists In The Db2 System Database Directory
+else:
+    print("\nThe database \"" + dbName + "\" has been deleted!\n")
+
+# Close The Db2 Server Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the local server ... Done!
+
+Dropping a database named MY_DB at the local server. Please wait.
+
+The database "MY_DB" has been deleted!
+
+Disconnecting from the local server ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
+

  Example 2: Delete a database stored on a remote server

+ +
+
+
+
+
+
In [2]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-dropdb_REMOTE.py                                                           #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.dropdb() API to      #
+#            delete (drop) a database stored on a remote Db2 server.                           #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.conn_errormsg()                                                       #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+hostName = "197.126.80.22"    # IP Address Of A Remote Server
+portNum = "50000"             # Port Number Used By Db2
+userID = "db2inst2"           # User ID (Recognized By The Remote Server)
+passWord = "ibmdb2"           # User Password
+svrConnection = None
+dbName = "MY_DB"
+returnCode = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Remote Db2 Server
+conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    svrConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Delete (Drop) A Database At The Remote Server
+print("Dropping a database named " + dbName + " at the " + hostName + " server. Please wait.")
+try:
+    returnCode = ibm_db.dropdb(svrConnection, dbName)
+except Exception:
+    pass
+
+# If The Database Could Not Be Deleted, Display An Error Message And Exit 
+if returnCode is False:
+    print("ERROR: Unable to drop the " + dbName + " database.\n")
+    errorMsg = ibm_db.conn_errormsg(svrConnection)
+    print(errorMsg + "\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Display A Status Message That States The Database Was Deleted And Close The
+# Db2 Server Connection That Was Opened Earlier
+else:
+    print("\nThe database \"" + dbName + "\" has been deleted!\n")
+    conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the 197.126.80.22 server ... Done!
+
+Dropping a database named MY_DB at the 197.126.80.22 server. Please wait.
+
+The database "MY_DB" has been deleted!
+
+Disconnecting from the 197.126.80.22 server ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-exec_immediate.html b/python_samples/HTML_Documentation/ibm_db-exec_immediate.html new file mode 100644 index 0000000..d9d1bdc --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-exec_immediate.html @@ -0,0 +1,13406 @@ + + + + +ibm_db-exec_immediate + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.exec_immediate()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Prepare and execute an SQL statement, using values supplied for parameter markers that were coded in the statement
(if any).

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.exec_immediate( IBM_DBConnectionconnection,stringstatement[, dictionaryoptions] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection        : A valid Db2 server or database connection.
  • +
  • SQLstatement   : A valid, executable SQL statement (that may or may not contain one or more parameter markers).
  • +
  • options              : A dictionary containing key-value pairs for the statement attributes that are to be set when the statement provided in the SQLstatement parameter is prepared. Valid keys and values are:

    +
      +
    • ibm_db.SQL_ATTR_CURSOR_TYPE                             : Specifies the type of cursor that is to be used for processing result sets. Valid values are:
        +
      • ibm_db.SQL_CURSOR_FORWARD_ONLY                 : A forward only cursor should be used (i.e., a cursor that only scrolls forward).
      • +
      • ibm_db. SQL_CURSOR_KEYSET_DRIVEN             : A keyset-driven cursor should be used.
      • +
      • ibm_db.SQL_CURSOR_STATIC                             : A static cursor should be used.
      • +
      • ibm_db.SQL_CURSOR_DYNAMIC                           : A dynamic, scrollable cursor that detects all changes to the result set, should be used. Dynamic cursors are only supported by Db2 for z/OS servers.
      • +
      +
    • +
    • ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH                 : Enables Db2 to determine the number of rows that are returned by a query (so the entire result set can be prefetched into memory, when possible); ibm_db.SQL_ROWCOUNT_PREFETCH_ON will turn this behavior ON and ibm_db.SQL_ROWCOUNT_PREFETCH_OFF will turn it OFF.
    • +
    • ibm_db.SQL_ATTR_QUERY_TIMEOUT                         : The number of seconds to wait for an SQL statement to execute before aborting and returning to the application. This option can be used to terminate long running queries — the default value of 0 means an application will wait indefinitely for the server to complete execution.
    • +
    +
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, a valid IBM_DBStatement object (that contains a result set if the SQL statement specified in the SQLstatement parameter was a SELECT statement).
  • +
  • If unsuccessful, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.exec_immediate() API is used to prepare and execute an SQL statement, using values supplied for parameter markers that were coded in the statement (if there are any).

+

If you plan to execute the same SQL statement repeatedly (with or without parameter marker values), consider using the ibm_db.prepare() and ibm_db.execute() APIs instead. Refer to the notebook for ibm_db.prepare() (i.e., the file ibm_db-prepare.ipynb) for a brief discussion of the advantages of using ibm_db.prepare() and ibm_db.execute(), as opposed to ibm_db.exec_immediate() to perform SQL operations against a Db2 database.

+

If the SQL statement executed returns a result set, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+

It is important to note that if you interject Python variables into the SQL statement used with this API, you run the risk of creating an application that is vunerable to SQL injection attacks . Consequently, if you want to execute SQL statements that contain parameter markers, it is recommended that you use the ibm_db.prepare() and ibm_db.execute() APIs to avoid creating a potential security exposure.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-exec_immediate.py                                                          #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.exec_immediate()     #
+#            API.                                                                              #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.fetch_row()                                                           #
+#                 ibm_db.result()                                                              #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT projno, projname FROM project WHERE prstaff < 2"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Query results:\n")
+print("PROJNO  PROJNAME")
+print("______  _____________________")
+
+# As Long As There Are Records In The Result Set Produced, ...
+while (ibm_db.fetch_row(resultSet) is True):
+
+    # Extract The Data Value For Each Column From The Current Record
+    projectNum = ibm_db.result(resultSet, 0)
+    projectName = ibm_db.result(resultSet, 1)
+
+    # Format And Display The Data Retrieved
+    print("{:6}  {:24}" .format(projectNum, projectName))
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT projno, projname FROM project WHERE prstaff < 2" ... Done!
+
+Query results:
+
+PROJNO  PROJNAME
+______  _____________________
+AD3112  PERSONNEL PROGRAMMING   
+IF2000  USER EDUCATION          
+OP2011  SCP SYSTEMS SUPPORT     
+OP2012  APPLICATIONS SUPPORT    
+OP2013  DB/DC SUPPORT           
+PL2100  WELD LINE PLANNING      
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-execute.html b/python_samples/HTML_Documentation/ibm_db-execute.html new file mode 100644 index 0000000..499260a --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-execute.html @@ -0,0 +1,13420 @@ + + + + +ibm_db-execute + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.execute()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Execute an SQL statement that has been prepared by the ibm_db.prepare() API.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.execute( IBM_DBStatementpreparedStmt[, tupleparamValues] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • preparedStmt    : A prepared SQL statement returned from the ibm_db.prepare() API.
  • +
  • paramValues     : A tuple that contains values for each parameter marker used in the prepared SQL statement specified in the preparedStmt parameter.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • True      : The prepared SQL statement specified in the preparedStmt parameter executed successfully.
  • +
  • False    : The prepared SQL statement specified in the preparedStmt parameter could not be executed.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.execute() API is used to execute an SQL statement that has been prepared by the ibm_db.prepare() API. If the SQL statement returns a result set, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+

Refer to the notebook for ibm_db.prepare() (i.e., the file ibm_db-prepare.ipynb) for a brief discussion of the advantages of using ibm_db.prepare() and ibm_db.execute(), as opposed to ibm_db.exec_immediate() to perform SQL operations against a Db2 database.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-execute.py                                                                 #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.execute() API.       #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.prepare()                                                             #
+#                 ibm_db.fetch_tuple()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+preparedStmt = False
+returnCode = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT projno, projname FROM project WHERE prstaff < 2"
+
+# Prepare The SQL Statement Just Defined
+print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit
+if preparedStmt is False:
+    print("\nERROR: Unable to prepare the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Execute The SQL Statement Just Prepared
+print("Executing the prepared SQL statement ... ", end="")
+try:
+    returnCode = ibm_db.execute(preparedStmt)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Query results:\n")
+print("PROJNO  PROJNAME")
+print("______  _____________________")
+
+# As Long As There Are Records In The Result Set Produced, ...
+noData = False
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Tuple
+    try:
+        dataRecord = ibm_db.fetch_tuple(preparedStmt)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop 
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Data Retrieved
+    else:
+        print("{:<6}  {:24}" .format(dataRecord[0], dataRecord[1])) 
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Preparing the SQL statement "SELECT projno, projname FROM project WHERE prstaff < 2" ... Done!
+
+Executing the prepared SQL statement ... Done!
+
+Query results:
+
+PROJNO  PROJNAME
+______  _____________________
+AD3112  PERSONNEL PROGRAMMING   
+IF2000  USER EDUCATION          
+OP2011  SCP SYSTEMS SUPPORT     
+OP2012  APPLICATIONS SUPPORT    
+OP2013  DB/DC SUPPORT           
+PL2100  WELD LINE PLANNING      
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-execute_many.html b/python_samples/HTML_Documentation/ibm_db-execute_many.html new file mode 100644 index 0000000..047f970 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-execute_many.html @@ -0,0 +1,13411 @@ + + + + +ibm_db-execute_many + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.execute_many()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Execute an SQL statement that has been prepared by the ibm_db.prepare() API, using the parameter sequences or mappings specified.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

mixed ibm_db.execute_many( IBM_DBStatementpreparedStmt,tupleseqOfParamValues)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • preparedStmt             : A prepared SQL statement returned from the ibm_db.prepare() API.
  • +
  • seqOfParamValues    : A tuple of tuples that contain values for each parameter marker used in the prepared SQL statement (that was speficied in the preparedStmt parameter).
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an integer representing the number of rows that were inserted, updated, or deleted by the SQL statement specified in the preparedStmt parameter.
  • +
  • If unsuccessful, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.execute_many() API is used to execute an SQL statement that has been prepared by the ibm_db.prepare() API, using a set of parameter sequences or mappings. Essentially, this API is used to perform bulk INSERT, UPDATE, and DELETE operations. (To achieve optimum performance, this API utilizes array input chaining to minimize the number of round trips that have to be made between the client and the server.)

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-execute_many.py                                                            #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.execute_many() API.  #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.prepare()                                                             #
+#                 ibm_db.fetch_tuple()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The get_row_count() Function That Has Been Defined In The File Named                  #
+# "ibm_db_tools.py"; This Function Contains The Programming Logic Needed To Obtain And         #
+# Display The Number Of Rows (Records) Found In A Db2 Database Table.                          #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import get_row_count
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+returnCode = None
+preparedStmt = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table
+returnCode = get_row_count(dbConnection, 'DEPARTMENT')
+if returnCode is False:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The INSERT Statement (With Parameter Markers) That Is To Be Used To Add Data
+# To The DEPARTMENT Table
+sqlStatement = "INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)"
+
+# Prepare The SQL Statement Just Defined
+print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit
+if preparedStmt is False:
+    print("\nERROR: Unable to prepare the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Create A List Of Data Values That Are To Be Supplied For The Parameter Markers Coded
+# In The INSERT Statement Specified
+pmValues = (('K22', 'SALES', '000110'), 
+            ('L22', 'FINANCE', '000120'), 
+            ('M22', 'HUMAN RESOURCES', '000130'))
+
+# Execute The SQL Statement Just Prepared
+print("Executing the prepared SQL statement ... ", end="")
+try:
+    returnCode = ibm_db.execute_many(preparedStmt, pmValues)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if returnCode is True:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message And Display The Number Of Records Added
+else:
+    print("Done!\n")
+    print("Number of records added : {}\n" .format(returnCode))
+
+    # Display The Number Of Rows That Exist In The DEPARTMENT Table Now
+    # (The Number Returned Should Reflect That Three Rows Were Added)
+    returnCode = get_row_count(dbConnection, 'DEPARTMENT')
+
+    # Close The Database Connection That Was Opened Earlier
+    conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Number of records found in the DEPARTMENT table: 14
+
+Preparing the SQL statement "INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)" ... Done!
+
+Executing the prepared SQL statement ... Done!
+
+Number of records added : 3
+
+Number of records found in the DEPARTMENT table: 17
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-fetch_assoc.html b/python_samples/HTML_Documentation/ibm_db-fetch_assoc.html new file mode 100644 index 0000000..1a32d06 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-fetch_assoc.html @@ -0,0 +1,13411 @@ + + + + +ibm_db-fetch_assoc + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.fetch_assoc()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve a row from a result set and copy its data to a dictionary.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

dictionary ibm_db.fetch_assoc( IBM_DBStatementstatement[, introwNumber] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement        : A valid IBM_DBStatement object that contains a result set.
  • +
  • rowNumber     : A specific, one-indexed, row in the result set that data is to be retrieved from.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+

When a rowNumber value is provided:

+
    +
  • If successful, a dictionary containing values for every column in the result set, for the row specified.
  • +
  • If unsuccessful or if the row specified doesn't exist, the value False.
  • +
+ +
+
+
+
+
+
+

When a rowNumber value is not provided:

+
    +
  • If successful, a dictionary containing values for every column in the result set, for the next row.
  • +
  • If unsuccessful or if there are no rows left in the result set, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.fetch_assoc() API is used to retrieve a row (record) from a result set and copy its data to a dictionary. Depending on how it is called, it can advance a cursor to the next row in a result set and copy the data for that row into a dictionary. Or, it can be used to retrieve the data for a specific row — provided a keyset-driven, dynamic, or static cursor is used to traverse the result set. (A warning will be issued if a specific row is requested and a forward-only cursor is used.)

+

In either case, the value for the first column in the row will be stored in the first key-value pair of the dictionary — the key will be the name of the column; the value will be the data for that column in the row. The second column will be stored in the second key-value pair, and so on.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-fetch_assoc.py                                                             #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.fetch_assoc() API.   #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT deptname FROM department WHERE admrdept = 'A00'"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Query results:\n")
+print("DEPTNAME")
+print("____________________________")
+
+# As Long As There Are Records In The Result Set Produced, ...
+noData = False
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop 
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Data Retrieved
+    else:
+        print("{:20}" .format(dataRecord['DEPTNAME']))
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT deptname FROM department WHERE admrdept = 'A00'" ... Done!
+
+Query results:
+
+DEPTNAME
+____________________________
+SPIFFY COMPUTER SERVICE DIV.
+PLANNING            
+INFORMATION CENTER  
+DEVELOPMENT CENTER  
+SUPPORT SERVICES    
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-fetch_both.html b/python_samples/HTML_Documentation/ibm_db-fetch_both.html new file mode 100644 index 0000000..6e17ef8 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-fetch_both.html @@ -0,0 +1,13412 @@ + + + + +ibm_db-fetch_both + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.fetch_both()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve a row from a result set and copy its data to both a tuple and a dictionary.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

tuple/dictionary ibm_db.fetch_both( IBM_DBStatementstatement[, introwNumber] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement        : A valid IBM_DBStatement object that contains a result set.
  • +
  • rowNumber     : A specific, one-indexed, row in the result set that data is to be retrieved from.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+

When a rowNumber value is provided:

+
    +
  • If successful, a tuple and a dictionary containing values for every column in the result set, for the row specified.
  • +
  • If unsuccessful or if the row specified doesn't exist, the value False.
  • +
+ +
+
+
+
+
+
+

When a rowNumber value is not provided:

+
    +
  • If successful, a tuple and dictionary containing values for every column in the result set, for the next row.
  • +
  • If unsuccessful or if there are no rows left in the result set, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.fetch_both() API is used to retrieve a row (record) from a result set and copy its data to both a tuple and a dictionary. Depending on how it is called, it can advance a cursor to the next row in a result set and copy the data for that row into a tuple and dictionary. Or, it can be used to retrieve the data for a specific row — provided a keyset-driven, dynamic, or static cursor is used to traverse the result set. (A warning will be issued if a specific row is requested and a forward-only cursor is used.)

+

In either case, the value for the first column in the row will be stored in the first position of the tuple returned (index position 0 ) and the first key-value pair of the dictionary returned, the second column will be stored in the second position/key-value pair, and so on.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-fetch_both.py                                                              #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.fetch_both() API.    #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT deptno, deptname FROM department WHERE admrdept = 'A00'"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Query results:\n")
+print("DEPTNO  DEPTNAME")
+print("______  ______________________")
+
+# As Long As There Are Records In The Result Set Produced, ...
+noData = False
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary And A Python Tuple
+    try:
+        dataRecord = ibm_db.fetch_both(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop 
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Data Retrieved
+    else:
+        print("{:6}  ".format(dataRecord[0]), end="")      # Tuple Value
+        print("{:20}" .format(dataRecord['DEPTNAME']))     # Dictionary Value
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT deptno, deptname FROM department WHERE admrdept = 'A00'" ... Done!
+
+Query results:
+
+DEPTNO  DEPTNAME
+______  ______________________
+A00     SPIFFY COMPUTER SERVICE DIV.
+B01     PLANNING            
+C01     INFORMATION CENTER  
+D01     DEVELOPMENT CENTER  
+E01     SUPPORT SERVICES    
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-fetch_row.html b/python_samples/HTML_Documentation/ibm_db-fetch_row.html new file mode 100644 index 0000000..927779b --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-fetch_row.html @@ -0,0 +1,13406 @@ + + + + +ibm_db-fetch_row + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.fetch_row()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Move a cursor to a specific row in a result set, or advance a cursor to the next row in a result set.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.fetch_row( IBM_DBStatementstatement[, introwNumber] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement        : A valid IBM_DBStatement object that contains a result set.
  • +
  • rowNumber     : A specific, one-indexed, row in the result set that data is to be retrieved from.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+

When a rowNumber value is provided:

+
    +
  • True      : The row specified exists in the result set.
  • +
  • False    : The row specified does not exist in the result set.
  • +
+ +
+
+
+
+
+
+

When a rowNumber value is not provided:

+
    +
  • True      : A row exists in the result set.
  • +
  • False    : There are no rows left in the result set.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.fetch_row() API is used to advance a cursor to the next row or move a cursor to a specific row in a result set. (A keyset-driven, dynamic, or static cursor must be used when moving a cursor to a specific row — a warning will be issued if a specific row is requested and a forward-only cursor is used.) Once a cursor has been moved to the appropriate row, the ibm_db.result() API can be used to retrieve data for individual columns in that row.

+

As an alternative to using the ibm_db.fetch_row() and ibm_db.result() APIs to iterate through a result set and retrieve data values for individual columns, applications can use the ibm_db.fetch_tuple(), ibm_db.fetch_assoc(), or ibm_db.fetch_both() API to position the cursor in a result set and retrieve the data for a complete row, in a single operation.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-fetch_row.py                                                               #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.fetch_row() API.     #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.result()                                                              #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+dataValue = None
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT deptname FROM department WHERE admrdept = 'A00'"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Query results:\n")
+print("DEPTNAME")
+print("____________________________")
+
+# As Long As There Are Records In The Result Set Produced, ...
+while (ibm_db.fetch_row(resultSet) is True):
+
+    # Retrieve The Data From The Current Row
+    try:
+        dataValue = ibm_db.result(resultSet, 0)
+    except Exception:
+        pass
+
+    # Display The Data Retrieved
+    if not dataValue is None:
+        print(dataValue)
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT deptname FROM department WHERE admrdept = 'A00'" ... Done!
+
+Query results:
+
+DEPTNAME
+____________________________
+SPIFFY COMPUTER SERVICE DIV.
+PLANNING
+INFORMATION CENTER
+DEVELOPMENT CENTER
+SUPPORT SERVICES
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-fetch_tuple.html b/python_samples/HTML_Documentation/ibm_db-fetch_tuple.html new file mode 100644 index 0000000..4dc98d3 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-fetch_tuple.html @@ -0,0 +1,13411 @@ + + + + +ibm_db-fetch_tuple + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.fetch_tuple()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve a row from a result set and copy its data to a tuple.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

tuple ibm_db.fetch_tuple( IBM_DBStatementstatement[, introwNumber] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement        : A valid IBM_DBStatement object that contains a result set.
  • +
  • rowNumber     : A specific, one-indexed, row in the result set that data is to be retrieved from.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+

When a rowNumber value is provided:

+
    +
  • If successful, a tuple containing values for every column in the result set, for the row specified.
  • +
  • If unsuccessful or if the row specified doesn't exist, the value False.
  • +
+ +
+
+
+
+
+
+

When a rowNumber value is not provided:

+
    +
  • If successful, a tuple containing values for every column in the result set, for the next row.
  • +
  • If unsuccessful or if there are no rows left in the result set, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.fetch_tuple() API is used to retrieve a row (record) from a result set and copy its data to a tuple. Depending on how it is called, it can advance a cursor to the next row in a result set and copy the data for that row into a tuple. Or, it can be used to retrieve the data for a specific row — provided a keyset driven, dynamic, or static cursor is used to traverse the result set. (A warning will be issued if a specific row is requested and a forward-only cursor is used.)

+

In either case, the value for the first column in the row will be stored in the first position of the tuple (index position 0 ), the second column will be stored in the second position (index position 1 ) and so on.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-fetch_tuple.py                                                             #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.fetch_tuple() API.   #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT deptname FROM department WHERE admrdept = 'A00'"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Query results:\n")
+print("DEPTNAME")
+print("____________________________")
+
+# As Long As There Are Records In The Result Set Produced, ...
+noData = False
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Tuple
+    try:
+        dataRecord = ibm_db.fetch_tuple(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop 
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Data Retrieved
+    else:
+        print(dataRecord[0]) 
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT deptname FROM department WHERE admrdept = 'A00'" ... Done!
+
+Query results:
+
+DEPTNAME
+____________________________
+SPIFFY COMPUTER SERVICE DIV.
+PLANNING
+INFORMATION CENTER
+DEVELOPMENT CENTER
+SUPPORT SERVICES
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-field_display_size.html b/python_samples/HTML_Documentation/ibm_db-field_display_size.html new file mode 100644 index 0000000..2b2e477 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-field_display_size.html @@ -0,0 +1,13423 @@ + + + + +ibm_db-field_display_size + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.field_display_size()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Determine the maximum number of bytes needed to display a column in a result set.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

int ibm_db.field_display_size( IBM_DBStatementstatement,mixedcolumn)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object that contains a result set.
  • +
  • column        : The zero-indexed position of the column or the name of the column in the result set that display size information is to be obtained for.
  • +
+ +
+
+
+
+
+
+

Return Values:

+
+
+
+
+
+
+
    +
  • If successful, an integer containing the maximum number of bytes required to display the column specified.
  • +
  • If unsuccessful or if the column doesn't exist, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.field_display_size() API is used to determine the maximum number of bytes needed to display the information stored in a column of a result set.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-field_display_size.py                                                      #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.field_display_size() #
+#            API.                                                                              #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.num_fields()                                                          #
+#                 ibm_db.field_name()                                                          #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+numColumns = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT * FROM employee"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed
+print("Examining the columns returned in the result set produced ... ", end="")
+try:
+    numColumns = ibm_db.num_fields(resultSet)
+except Exception:
+    pass
+
+# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error
+# Message And Exit 
+if numColumns is False:
+    print("\nERROR: Unable to obtain information about the result set produced.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Result set information:\n")
+print("COLUMN NAME  DATA DISPLAY SIZE")
+print("___________  _________________")
+
+# As Long As There Is Column Information, ...
+for loopCounter in range(0, numColumns):
+
+    # Get The Name Of The Current Column
+    colName = ibm_db.field_name(resultSet, loopCounter)
+
+    # Get The Display Size Of The Data For The Current Column
+    colDispSize = ibm_db.field_display_size(resultSet, loopCounter)
+
+    # Format And Display The Data Retrieved
+    if (not colName is False) and (not colDispSize is False):
+        print("{:<13}  {:>15}" .format(colName, colDispSize))
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT * FROM employee" ... Done!
+
+Examining the columns returned in the result set produced ... Done!
+
+Result set information:
+
+COLUMN NAME  DATA DISPLAY SIZE
+___________  _________________
+EMPNO                        6
+FIRSTNME                    12
+MIDINIT                      1
+LASTNAME                    15
+WORKDEPT                     3
+PHONENO                      4
+HIREDATE                    10
+JOB                          8
+EDLEVEL                      6
+SEX                          1
+BIRTHDATE                   10
+SALARY                      11
+BONUS                       11
+COMM                        11
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-field_name.html b/python_samples/HTML_Documentation/ibm_db-field_name.html new file mode 100644 index 0000000..71dbcb6 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-field_name.html @@ -0,0 +1,13419 @@ + + + + +ibm_db-field_name + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.field_name()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Determine the name of a column in a result set.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

string ibm_db.field_name( IBM_DBStatementstatement,mixedcolumn)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object that contains a result set.
  • +
  • column        : The zero-indexed position of the column or the name of the column in the result set that column name information is to be obtained for.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, a character string containing the name of the column specified.
  • +
  • If unsuccessful or if the column doesn't exist, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.field_name() API is used to determine the name of a column in a result set.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-field_name.py                                                              #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.field_name() API.    #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.num_fields()                                                          #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+numColumns = False
+colName = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT * FROM employee"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed
+print("Examining the columns returned in the result set produced ... ", end="")
+try:
+    numColumns = ibm_db.num_fields(resultSet)
+except Exception:
+    pass
+ 
+# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error
+# Message And Exit 
+if numColumns is False:
+    print("\nERROR: Unable to obtain information about the result set produced.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+    
+# Display A Report Header
+print("Result set information:\n")
+print("COLUMN NUMBER  COLUMN NAME")
+print("_____________  ___________")
+
+# As Long As There Is Column Information, ...
+for loopCounter in range(0, numColumns):
+
+    # Get The Name Of The Current Column
+    colName = ibm_db.field_name(resultSet, loopCounter)
+
+    # Format And Display The Data Retrieved
+    if not colName is False:
+        print("{:>13}  {:<11}" .format(loopCounter, colName))
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT * FROM employee" ... Done!
+
+Examining the columns returned in the result set produced ... Done!
+
+Result set information:
+
+COLUMN NUMBER  COLUMN NAME
+_____________  ___________
+            0  EMPNO      
+            1  FIRSTNME   
+            2  MIDINIT    
+            3  LASTNAME   
+            4  WORKDEPT   
+            5  PHONENO    
+            6  HIREDATE   
+            7  JOB        
+            8  EDLEVEL    
+            9  SEX        
+           10  BIRTHDATE  
+           11  SALARY     
+           12  BONUS      
+           13  COMM       
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-field_num.html b/python_samples/HTML_Documentation/ibm_db-field_num.html new file mode 100644 index 0000000..f41a97c --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-field_num.html @@ -0,0 +1,13380 @@ + + + + +ibm_db-field_num + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.field_num()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Determine the position of a column in a result set.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

int ibm_db.field_num( IBM_DBStatementstatement,mixedcolumn)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object that contains a result set.
  • +
  • column        : The zero-indexed position of the column or the name of the column in the result set that position information is to be obtained for.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an integer containing the zero-indexed position of the column specified.
  • +
  • If unsuccessful or if the column doesn't exist, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.field_num() API is used to determine the ordinal position, starting from zero, of a column in a result set.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-field_num.py                                                               #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.field_num() API.     #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+columnNumber = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT * FROM employee"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Find Out Which Column In The Result Set Produced By The Query Just Executed Contains Data 
+# That Was Retrieved From The "BIRTHDATE" Column Of The Table
+try:
+    columnNumber = ibm_db.field_num(resultSet, 'BIRTHDATE')
+except Exception:
+    pass
+
+# If The Column Number For The "BIRTHDATE" Column Could Not Be Obtained, Display An Error
+# Message And Exit 
+if columnNumber is False:
+    print("\nERROR: Unable to obtain information about the result set produced.")
+    conn.closeConnection()
+    exit(-1)
+
+# Format And Display The Data Retrieved
+print("\'BIRTHDATE\' data can be found in column number {:<2} " .format(columnNumber), end="")
+print("of the result set produced.\n")
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT * FROM employee" ... Done!
+
+'BIRTHDATE' data can be found in column number 10 of the result set produced.
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-field_precision.html b/python_samples/HTML_Documentation/ibm_db-field_precision.html new file mode 100644 index 0000000..5e68e6c --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-field_precision.html @@ -0,0 +1,13412 @@ + + + + +ibm_db-field_precision + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.field_precision()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Determine the precision of a column in a result set.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

int ibm_db.field_precision( IBM_DBStatementstatement,mixedcolumn)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object that contains a result set.
  • +
  • column        : The zero-indexed position of the column or the name of the column in the result set that precision information is to be obtained for.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an integer containing the precision of the column specified.
  • +
  • If unsuccessful or if the column doesn't exist, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.field_precision() API is used to determine the precision (i.e., total number of digits) of a column in a result set.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-field_precision.py                                                         #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.field_precision()    #
+#            API.                                                                              #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.num_fields()                                                          #
+#                 ibm_db.field_name()                                                          #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+numColumns = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT salary, bonus, comm FROM employee"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed
+print("Examining the columns returned in the result set produced ... ", end="")
+try:
+    numColumns = ibm_db.num_fields(resultSet)
+except Exception:
+    pass
+ 
+# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error
+# Message And Exit 
+if numColumns is False:
+    print("\nERROR: Unable to obtain information about the result set produced.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Result set information:\n")
+print("COLUMN NAME  PRECISION (TOTAL NUMBER OF DIGITS)")
+print("___________  __________________________________")
+
+# As Long As There Is Column Information, ...
+for loopCounter in range(0, numColumns):
+
+    # Get The Name Of The Current Column
+    colName = ibm_db.field_name(resultSet, loopCounter)
+
+    # Get The Precision Of The Current Column
+    colPrecision = ibm_db.field_precision(resultSet, loopCounter)
+
+    # Format And Display The Data Retrieved
+    if (not colName is False) and (not colPrecision is False):
+        print("{:<13}  {:>32}" .format(colName, colPrecision))
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT salary, bonus, comm FROM employee" ... Done!
+
+Examining the columns returned in the result set produced ... Done!
+
+Result set information:
+
+COLUMN NAME  PRECISION (TOTAL NUMBER OF DIGITS)
+___________  __________________________________
+SALARY                                        9
+BONUS                                         9
+COMM                                          9
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-field_scale.html b/python_samples/HTML_Documentation/ibm_db-field_scale.html new file mode 100644 index 0000000..1053f81 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-field_scale.html @@ -0,0 +1,13411 @@ + + + + +ibm_db-field_scale + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.field_scale()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Determine the scale of a column in a result set.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

int ibm_db.field_scale( IBM_DBStatementstatement,mixedcolumn)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object that contains a result set.
  • +
  • column        : The zero-indexed position of the column or the name of the column in the result set that scale information is to be obtained for.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an integer containing the scale of the column specified.
  • +
  • If unsuccessful or if the column doesn't exist, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.field_scale() API is used to determine the scale (i.e., number of decimal digits) of a column in a result set.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-field_scale.py                                                             #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.field_scale() API.   #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.num_fields()                                                          #
+#                 ibm_db.field_name()                                                          #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+numColumns = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT salary, bonus, comm FROM employee"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed
+print("Examining the columns returned in the result set produced ... ", end="")
+try:
+    numColumns = ibm_db.num_fields(resultSet)
+except Exception:
+    pass
+ 
+# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error
+# Message And Exit 
+if numColumns is False:
+    print("\nERROR: Unable to obtain information about the result set produced.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Result set information:\n")
+print("COLUMN NAME  SCALE (DECIMAL DIGITS)")
+print("___________  ______________________")
+
+# As Long As There Is Column Information, ...
+for loopCounter in range(0, numColumns):
+
+    # Get The Name Of The Current Column
+    colName = ibm_db.field_name(resultSet, loopCounter)
+
+    # Get The Scale Of The Current Column
+    colScale = ibm_db.field_scale(resultSet, loopCounter)
+
+    # Format And Display The Data Retrieved
+    if (not colName is False) and (not colScale is False):
+        print("{:<13}  {:>20}" .format(colName, colScale))
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT salary, bonus, comm FROM employee" ... Done!
+
+Examining the columns returned in the result set produced ... Done!
+
+Result set information:
+
+COLUMN NAME  SCALE (DECIMAL DIGITS)
+___________  ______________________
+SALARY                            2
+BONUS                             2
+COMM                              2
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-field_type.html b/python_samples/HTML_Documentation/ibm_db-field_type.html new file mode 100644 index 0000000..47cca01 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-field_type.html @@ -0,0 +1,13422 @@ + + + + +ibm_db-field_type + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.field_type()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Determine the data type of a column in a result set.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

string ibm_db.field_type( IBM_DBStatementstatement,mixedcolumn)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object that contains a result set.
  • +
  • column        : The zero-indexed position of the column or the name of the column in the result set that data type information is to be obtained for.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, a string containing the data type of the column specified.
  • +
  • If unsuccessful or if the column doesn't exist, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.field_type() API is used to obtain a string representation of the SQL data type of a column in a result set.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-field_type.py                                                              #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.field_type() API.    #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.num_fields()                                                          #
+#                 ibm_db.field_name()                                                          #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+numColumns = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT * FROM employee"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed
+print("Examining the columns returned in the result set produced ... ", end="")
+try:
+    numColumns = ibm_db.num_fields(resultSet)
+except Exception:
+    pass
+ 
+# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error
+# Message And Exit 
+if numColumns is False:
+    print("\nERROR: Unable to obtain information about the result set produced.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Result set information:\n")
+print("COLUMN NAME  DATA TYPE")
+print("___________  _________")
+
+# As Long As There Is Column Information, ...
+for loopCounter in range(0, numColumns):
+
+    # Get The Name Of The Current Column
+    colName = ibm_db.field_name(resultSet, loopCounter)
+
+    # Get The Data Type Of The Current Column
+    colDataType = ibm_db.field_type(resultSet, loopCounter)
+
+    # Format And Display The Data Retrieved - Show Data Types In Upper Case
+    if (not colName is False) and (not colDataType is False):
+        print("{:<13}  {:>7}" .format(colName, colDataType.upper()))
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT * FROM employee" ... Done!
+
+Examining the columns returned in the result set produced ... Done!
+
+Result set information:
+
+COLUMN NAME  DATA TYPE
+___________  _________
+EMPNO           STRING
+FIRSTNME        STRING
+MIDINIT         STRING
+LASTNAME        STRING
+WORKDEPT        STRING
+PHONENO         STRING
+HIREDATE          DATE
+JOB             STRING
+EDLEVEL            INT
+SEX             STRING
+BIRTHDATE         DATE
+SALARY         DECIMAL
+BONUS          DECIMAL
+COMM           DECIMAL
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-field_width.html b/python_samples/HTML_Documentation/ibm_db-field_width.html new file mode 100644 index 0000000..cfaedd9 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-field_width.html @@ -0,0 +1,13411 @@ + + + + +ibm_db-field_width + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.field_width()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Determine the width (size) of a column in a result set.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

int ibm_db.field_width( IBM_DBStatementstatement,mixedcolumn)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object that contains a result set.
  • +
  • column        : The zero-indexed position of the column or the name of the column in the result set that width information is to be obtained for.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an integer containing the width of the column specified.
  • +
  • If unsuccessful or if the column doesn't exist, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.field_width() API is used to determine the width (size) of a column in a result set. That is, the maximum width of the column if it has a fixed-length data type and the actual width of the column if it has a variable-length data type.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-field_width.py                                                             #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.field_width() API.   #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.num_fields()                                                          #
+#                 ibm_db.field_name()                                                          #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+numColumns = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT * FROM emp_resume"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed
+print("Examining the columns returned in the result set produced ... ", end="")
+try:
+    numColumns = ibm_db.num_fields(resultSet)
+except Exception:
+    pass
+ 
+# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error
+# Message And Exit 
+if numColumns is False:
+    print("\nERROR: Unable to obtain information about the result set produced.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Result set information:\n")
+print("COLUMN NAME    MAXIMUM VALUE SIZE (IN BYTES)")
+print("_____________  _____________________________")
+
+# As Long As There Is Column Information, ...
+for loopCounter in range(0, numColumns):
+
+    # Get The Name Of The Current Column
+    colName = ibm_db.field_name(resultSet, loopCounter)
+
+    # Get The Size Of The Data Allowed In The Current Column
+    colWidth = ibm_db.field_width(resultSet, loopCounter)
+
+    # Format And Display The Data Retrieved
+    if (not colName is False) and (not colWidth is False):
+        print("{:<13}  {:>29}" .format(colName, colWidth))
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT * FROM emp_resume" ... Done!
+
+Examining the columns returned in the result set produced ... Done!
+
+Result set information:
+
+COLUMN NAME    MAXIMUM VALUE SIZE (IN BYTES)
+_____________  _____________________________
+EMPNO                                      6
+RESUME_FORMAT                             10
+RESUME                                  5120
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-foreign_keys.html b/python_samples/HTML_Documentation/ibm_db-foreign_keys.html new file mode 100644 index 0000000..ae116c0 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-foreign_keys.html @@ -0,0 +1,13507 @@ + + + + +ibm_db-foreign_keys + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.foreign_keys()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve information about the columns that participate in foreign keys that reference a table.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.foreign_keys( IBM_DBConnectionconnection,stringqualifierName,stringschemaName,stringtableName)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection        : A valid Db2 server or database connection.
  • +
  • qualifierName    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value None or an empty string ('') for Db2 databases on other operating systems.
  • +
  • schemaName     : The name of the schema that contains the table(s) that foreign key information is to be obtained for. To use the schema associated with the current connection, provide the value None.
  • +
  • tableName          : The name of the table(s) that foreign key information is to be obtained for.
  • +
+ +
+
+
+
+
+
+

Return Values:

+
+
+
+
+
+
+
    +
  • If successful, an IBM_DBStatement with a result set that contains the following information:

    +
      +
    • PK_NAME                : The name of the primary key.
    • +
    • PKTABLE_CAT        : The name of the catalog associated with the schema and table that contains the primary key; Db2 does not use catalogs so this field will always contain the value None. (Db2 databases on OS/390 or z/OS servers can return information in this field.)
    • +
    • PKTABLE_SCHEM    : The name of the schema for the table that contains the primary key.
    • +
    • PKTABLE_NAME      : The name of the table that contains the primary key.
    • +
    • PKCOLUMN_NAME    : The name of a primary key column.
    • +
    • FK_NAME                : The name of the foreign key.
    • +
    • FKTABLE_CAT        : The name of the catalog associated with the schema and table that contains the foreign key; Db2 does not use catalogs so this field will always contain the value None. (Db2 databases on OS/390 or z/OS servers can return information in this field.)
    • +
    • FKTABLE_SCHEM    : The name of the schema for the table that contains the foreign key.
    • +
    • FKTABLE_NAME      : The name of the table that contains the foreign key.
    • +
    • FKCOLUMN_NAME    : The name of a foreign key column.
    • +
    • KEY_SEQ                : The FKCOLUMN_NAME column's ordinal position in the foreign key, starting from 1.
    • +
    • UPDATE_RULE        : The action to be applied to the foreign key when an UPDATE operation is performed.
    • +
    • DELETE_RULE        : The action to be applied to the foreign key when a UDELETE operation is performed.
    • +
    • DEFERRABILITY    : Indication of whether the foreign key is deferred initially and applied later, applied immediately, or cannot be deferred.

    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.foreign_keys API is used to retrieve information about the columns that participate in foreign keys that reference a table.

+

The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-foreign_keys.py                                                            #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.foreign_keys() API.  #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.tables()                                                              #
+#                 ibm_db.fetch_assoc()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+schemaName = userID.upper()
+tableName = "PROJECT"
+resultSet = False
+dataRecord = False
+foreignKeyRules = {0 : "CASCADE", 1 : "RESTRICT", 2 : "SET_NULL", 3 : "NO_ACTION", 
+                   4 : "SET_DEFAULT"}
+deferability = {5 : "INITIALLY_DEFERRED", 6 : "INITIALLY_IMMEDIATE", 
+                7 : "NOT_DEFERRABLE"}
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Retrieve Information About All Of The Tables In The Current User's Schema
+print("Obtaining information about tables in the " + schemaName + " schema ... ", end="")
+try:
+    resultSet = ibm_db.tables(dbConnection, None, schemaName, None, 'TABLE')
+except Exception:
+    pass
+
+# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit
+if resultSet is False:
+    print("\nERROR: Unable to obtain the information desired\n.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# As Long As There Are Records (That Were Produced By The ibm_db.tables API), ... 
+tableList = []
+noData = False
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop  
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Store The Table Name Retrieved In A Python List (This List Will Be Used
+    # Later To Skip Records Associated With Aliases)
+    else:
+        tableList.append(dataRecord['TABLE_NAME'])
+
+# Attempt To Retrieve Information About All Of The Foreign Keys That Have Been Defined For 
+# The Table Specified
+print("Obtaining information about foreign keys created for ", end="")
+print("the " + schemaName + "." + tableName + " table ... ", end="")
+resultSet = False
+try:
+    resultSet = ibm_db.foreign_keys(dbConnection, None, schemaName, tableName)
+except Exception:
+    pass
+
+# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit
+if resultSet is False:
+    print("\nERROR: Unable to obtain the information desired\n.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# As Long As There Are Records (That Were Produced By The ibm_db.foreign_keys API), ...
+noData = False
+loopCounter = 1
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop  
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Data Retrieved (Skip Information For Aliases)
+    else:
+
+        # If The Current Data Record Is For A Table Alias, Ignore It
+        if not dataRecord['FKTABLE_NAME'] in tableList:
+            continue
+
+        # Display Record Header Information
+        print("Foreign key " + str(loopCounter) + " details:")
+        print("______________________________________________")
+
+        # Display The Information Stored In The Data Record Retrieved
+        print("Primary key name    : {}" .format(dataRecord['PK_NAME']))
+        print("  Table schema      : {}" .format(dataRecord['PKTABLE_SCHEM']))
+        print("  Table name        : {}" .format(dataRecord['PKTABLE_NAME']))
+        print("  Column name       : {}" .format(dataRecord['PKCOLUMN_NAME']))
+        print("Foreign key name    : {}" .format(dataRecord['FK_NAME']))
+        print("  Table schema      : {}" .format(dataRecord['FKTABLE_SCHEM']))
+        print("  Table name        : {}" .format(dataRecord['FKTABLE_NAME']))
+        print("  Column name       : {}" .format(dataRecord['FKCOLUMN_NAME']))
+        print("  Column number     : {}" .format(dataRecord['KEY_SEQ']))
+        print("  UPDATE rule used  : ", end="")
+        print(foreignKeyRules.get(dataRecord['UPDATE_RULE']))
+        print("  DELETE rule used  : ", end="")
+        print(foreignKeyRules.get(dataRecord['DELETE_RULE']))
+        print("  Deferability      : ", end="")
+        print(deferability.get(dataRecord['DEFERRABILITY']))
+
+        # Increment The loopCounter Variable And Print A Blank Line To Separate Foreign Key
+        # Records From Each Other
+        loopCounter += 1
+        print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Obtaining information about tables in the DB2INST1 schema ... Done!
+
+Obtaining information about foreign keys created for the DB2INST1.PROJECT table ... Done!
+
+Foreign key 1 details:
+______________________________________________
+Primary key name    : PK_PROJECT
+  Table schema      : DB2INST1
+  Table name        : PROJECT
+  Column name       : PROJNO
+Foreign key name    : RPAP
+  Table schema      : DB2INST1
+  Table name        : PROJACT
+  Column name       : PROJNO
+  Column number     : 1
+  UPDATE rule used  : NO_ACTION
+  DELETE rule used  : RESTRICT
+  Deferability      : NOT_DEFERRABLE
+
+Foreign key 2 details:
+______________________________________________
+Primary key name    : PK_PROJECT
+  Table schema      : DB2INST1
+  Table name        : PROJECT
+  Column name       : PROJNO
+Foreign key name    : RPP
+  Table schema      : DB2INST1
+  Table name        : PROJECT
+  Column name       : MAJPROJ
+  Column number     : 1
+  UPDATE rule used  : NO_ACTION
+  DELETE rule used  : CASCADE
+  Deferability      : NOT_DEFERRABLE
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-free_result.html b/python_samples/HTML_Documentation/ibm_db-free_result.html new file mode 100644 index 0000000..5862acc --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-free_result.html @@ -0,0 +1,13475 @@ + + + + +ibm_db-free_result + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.free_result()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Free all system resources associated with an IBM_DBStatement object.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.free_result( IBM_DBStatementstatement)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • True      : System resources associated with the IBM_DBStatement object were freed.
  • +
  • False    : System resources associated with the IBM_DBStatement object could not be freed.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.free_result() API is used to stop all processing, discard all pending results, close any open cursors, and free all memory associated with a specific IBM_DBStatement object. This work is done automatically when an application ends and control is returned to the operating system. However, the ibm_db.free_result() API provides a way to explicitly perform these operations, when appropriate, while an application is running.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-free_result.py                                                             #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.free_result() API    #
+#            to free system resources associated with a prepared SQL statement.                #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.prepare()                                                             #
+#                 ibm_db.execute()                                                             #
+#                 ibm_db.num_rows()                                                            #
+#                 ibm_db.set_option()                                                          #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+preparedStmt = False
+resultSet = False
+returnCode = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT * FROM employee WHERE edlevel > 17"
+
+# Prepare The SQL Statement Just Defined
+print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit
+if preparedStmt is False:
+    print("\nERROR: Unable to prepare the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Execute The SQL Statement Just Prepared
+print("Executing the prepared SQL statement ... ", end="")
+try:
+    resultSet = ibm_db.execute(preparedStmt)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Just Executed
+# (This Information Should Not Be Available)
+try:
+    numRows = ibm_db.num_rows(preparedStmt)
+except Exception:
+    pass
+ 
+# Display An Appropriate Message, Based On The Information Returned
+if numRows <= 0:
+    print("Unable to obtain information about the number of rows returned.\n")
+else:
+    print("Number of rows returned by the query: " + str(numRows) + "\n")
+
+# Free System Resources That Are Associated With The Prepared Statement And Result Set Produced
+print("Freeing system resources associated with the prepared statement ... ", end="")
+try:
+    returnCode = ibm_db.free_result(preparedStmt)
+except Exception:
+    pass
+
+# If The Appropriate System Resources Could Not Be Freed, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to free the appropriate system resources.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Create A Dictionary That Contains The Value Needed To Turn Row Prefetch Behavior On;
+# This Enables Db2 To Determine The Number Of Rows That Are Returned By A Query (So The
+# Entire Result Set Can Be Prefetched Into Memory, When Possible) 
+stmtOption = {ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON}
+
+# Attempt To Set The Statement Option Specified
+print("Turning SQL_ATTR_ROWCOUNT_PREFETCH behavior ON ... ", end="")
+try:
+    returnCode = ibm_db.set_option(preparedStmt, stmtOption, 0)
+except Exception:
+    pass
+
+# If The Statement Option Could Not Be Set, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to set the statement option specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Execute The Prepared SQL Statement Again
+print("Executing the prepared SQL statement again ... ", end="")
+try:
+    resultSet = ibm_db.execute(preparedStmt)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Again
+# (This Time, The Information Should Be Available)
+try:
+    numRows = ibm_db.num_rows(preparedStmt)
+except Exception:
+    pass
+
+# Display An Appropriate Message, Based On The New Information Returned
+if numRows <= 0:
+    print("Unable to obtain information about the number of rows returned.\n")
+else:
+    print("Number of rows returned by the query: " + str(numRows) + "\n")
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Preparing the SQL statement "SELECT * FROM employee WHERE edlevel > 17" ... Done!
+
+Executing the prepared SQL statement ... Done!
+
+Unable to obtain information about the number of rows returned.
+
+Freeing system resources associated with the prepared statement ... Done!
+
+Turning SQL_ATTR_ROWCOUNT_PREFETCH behavior ON ... Done!
+
+Executing the prepared SQL statement again ... Done!
+
+Number of rows returned by the query: 9
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-get_option.html b/python_samples/HTML_Documentation/ibm_db-get_option.html new file mode 100644 index 0000000..3a55744 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-get_option.html @@ -0,0 +1,13620 @@ + + + + +ibm_db-get_option + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.get_option()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve the current value of a connection or statement option (attribute).

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

mixed ibm_db.get_option( mixedresource,intoptions,intresourceType)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • resource            : A valid IBM_DBConnection or IBM_DBStatement object.
  • +
  • options              : A valid key for the attribute whose value is to be retrieved. Valid keys for IBM_DBConnection objects are:

    +
      +
    • ibm_db.SQL_ATTR_AUTOCOMMIT                               : Indicates whether AUTOCOMMIT mode is being used or not; ibm_db.SQL_AUTOCOMMIT_ON will be returned if AUTOCOMMIT behavior is ON and ibm_db.SQL_AUTOCOMMIT_OFF will be returned if it is OFF.
    • +
    • ibm_db.SQL_ATTR_CASE                                           : The case that column names will be returned in; ibm_db.CASE_NATURAL will cause column names to be returned in natural case, ibm_db.CASE_LOWER will cause them to be returned in lower case, and ibm_db.CASE_UPPER will cause them to be returned in upper case. (This attribute can only be used with Db2 databases on OS/390 or z/OS servers.)
    • +
    • ibm_db.SQL_ATTR_CURRENT_SCHEMA                       : The name of the schema that is used, by default, when operations that require a schema name are performed and no schema name is provided.
    • +
    • ibm_db.SQL_ATTR_INFO_ACCTSTR                           : The client accounting string (that may have been sent to the currently connected Db2 server or database).
    • +
    • ibm_db.SQL_ATTR_INFO_APPLNAME                         : The client application name (that may have been sent to the currently connected Db2 server or database).
    • +
    • ibm_db.SQL_ATTR_INFO_PROGRAMNAME                   : The name of the application being run (on the client).
    • +
    • ibm_db.SQL_ATTR_INFO_USERID                             : The client user ID (accounting user ID) that may have been sent to the currently connected Db2 server or database. This information is used for identification purposes only—not for authentication.
    • +
    • ibm_db.SQL_ATTR_INFO_WRKSTNNAME                     : The client workstation name (that may have been sent to the currently connected Db2 server or database).
    • +
    • ibm_db.SQL_ATTR_USE_TRUSTED_CONTEXT             : Indicates whether the connection to a Db2 server or database being used is treated as a trusted connection; ibm_db.SQL_TRUE indicates a trusted connection is being used and ibm_db.SQL_FALSE indicates a trusted connection is not.
    • +
    • ibm_db.SQL_ATTR_TRUSTED_CONTEXT_USERID       : The client user ID (accounting user ID) that the trusted connection being used has been switched to.
    • +
    • ibm_db.SQL_ATTR_TRUSTED_CONTEXT_PASSWORD   : The password for the ibm_db.SQL_ATTR_TRUSTED_CONTEXT_USERID user.

    • +
    +

    Valid keys for IBM_DBStatement objects are:

    +
      +
    • ibm_db.SQL_ATTR_CURSOR_TYPE                             : The type of cursor that is being used to process result sets. Valid values are:
        +
      • ibm_db.SQL_CURSOR_FORWARD_ONLY                 : A forward only cursor is being used.
      • +
      • ibm_db. SQL_CURSOR_KEYSET_DRIVEN             : A keyset-driven cursor is being used.
      • +
      • ibm_db.SQL_CURSOR_STATIC                             : A static cursor is being used.
      • +
      • ibm_db.SQL_CURSOR_DYNAMIC                           : A dynamic, scrollable cursor is being used. Dynamic cursors are only supported by Db2 for z/OS servers.
      • +
      +
    • +
    • ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH                 : Identifies whether Db2 will try to determine the number of rows that will be returned by a query; ibm_db.SQL_ROWCOUNT_PREFETCH_ON will be returned if this behavior is turned ON and ibm_db.SQL_ROWCOUNT_PREFETCH_OFF if it is turned OFF.
    • +
    • ibm_db.SQL_ATTR_QUERY_TIMEOUT                         : The number of seconds Db2 will wait for an SQL statement to execute before aborting and returning to the application. A value of 0 indicates applications will wait indefinitely for the server to complete execution.

    • +
    +
  • +
  • resourceType    : Identifies whether the value provided in the resource parameter is an IBM_DBConnection object or an IBM_DBStatement object. Valid values for this parameter are:

    +
      +
    • 0   : The resource parameter contains a valid IBM_DBStatement object.
    • +
    • 1   : The resource parameter contains a valid IBM_DBConnection object.
    • +
    +
  • +
+ +
+
+
+
+
+
+

Return Values:

+
+
+
+
+
+
+
    +
  • If successful, the current setting of the option specified.
  • +
  • If unsuccessful, a Python interpreter error.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.get_option API is used to retrieve the current setting of a specific connection or statement option (attribute).

+ +
+
+
+
+
+
+

Examples:

+
+
+
+
+
+
+

    Example 1: Get connection options

+ +
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-get_option_CONNECTION.py                                                   #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.get_option() API to  #
+#            obtain the values that have been assigned to some of the connection options       #
+#            available.                                                                        #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.connect()                                                             #
+#                 ibm_db.close()                                                               #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+
+# Create A Dictionary That Contains Connection Options That Can Be Set Before A Database
+# Connection Is Established
+connectOptions = {ibm_db.SQL_ATTR_AUTOCOMMIT : ibm_db.SQL_AUTOCOMMIT_ON,
+    ibm_db.SQL_ATTR_CURRENT_SCHEMA : 'db2inst1',
+    ibm_db.SQL_ATTR_INFO_PROGRAMNAME : 'ibm_db-get_option.py'}
+
+# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database
+# Is About To Be Made
+print("\nConnecting to the \'" + dbName + "\' database ... ", end="")
+
+# Construct The String That Will Be Used To Establish A Db2 Database Connection
+connString = "ATTACH=FALSE"              # Attach To A Database; Not A Server
+connString += ";DATABASE=" + dbName      # Required To Connect To A Database     
+connString += ";PROTOCOL=TCPIP"
+connString += ";UID=" + userID
+connString += ";PWD=" + passWord
+
+# Attempt To Establish A Connection To The Database Specified (And Set The Appropriate
+# Connection Options) 
+try:
+    dbConnection = ibm_db.connect(connString, '', '', connectOptions)
+except Exception:
+    pass
+
+# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit
+if dbConnection is None:
+    print("\nERROR: Unable to connect to the \'" + dbName + "\' database.")
+    print("Connection string used: " + connString + "\n")
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Connection option settings:\n")
+print("OPTION                     SETTING")
+print("_________________________  ____________________")
+
+# Retrieve And Display The Ordinal Value For The Current AUTOCOMMIT Setting
+value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_AUTOCOMMIT, 1)
+print("SQL_ATTR_AUTOCOMMIT        ", end="")
+print(ord(value))
+
+# Retrieve And Display The Schema Name That Was Set During The Connection
+value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_CURRENT_SCHEMA, 1)
+print("SQL_ATTR_CURRENT_SCHEMA    " + value)
+
+# Retrieve And Display The Program Name That Was Set During The Connection
+value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_PROGRAMNAME, 1)
+print("SQL_ATTR_INFO_PROGRAMNAME  " + value)
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Attempt To Close The Db2 Database Connection That Was Opened Earlier
+if not dbConnection is None:
+    print("Disconnecting from the \'" + dbName + "\' database ... ", end="")
+    try:
+        returnCode = ibm_db.close(dbConnection)
+    except Exception:
+        pass
+
+    # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit
+    if returnCode is False:
+        print("\nERROR: Unable to disconnect from the " + dbName + " database.")
+        exit(-1)
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!\n")
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the 'SAMPLE' database ... Done!
+
+Connection option settings:
+
+OPTION                     SETTING
+_________________________  ____________________
+SQL_ATTR_AUTOCOMMIT        1
+SQL_ATTR_CURRENT_SCHEMA    db2inst1
+SQL_ATTR_INFO_PROGRAMNAME  ibm_db-get_option.py
+
+Disconnecting from the 'SAMPLE' database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
+

    Example 2: Get statement option

+ +
+
+
+
+
+
In [2]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-get_option_STATEMENT.py                                                    #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.get_option() API to  #
+#            assign a value to one of the statement options available.                         #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+cursorType = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Create A Dictionary That Contains Values For All Of The Statement Options That Can Be Set 
+stmtOptions = {ibm_db.SQL_ATTR_CURSOR_TYPE : ibm_db.SQL_CURSOR_STATIC,
+    ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON,
+    ibm_db.SQL_ATTR_QUERY_TIMEOUT : 10}
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT * FROM employee WHERE edlevel > 17"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement, stmtOptions)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified
+print("Obtaining information about the type of cursor being used ... ", end="")
+try:
+    cursorType = ibm_db.get_option(resultSet, ibm_db.SQL_ATTR_CURSOR_TYPE, 0)
+except Exception:
+    pass
+
+# If Information About The Cursor Could Not Be Obtained, Display An Error Message And Exit 
+if cursorType is False:
+    print("\nERROR: Unable to obtain the information desired.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified
+print("Type of cursor specified : Static (SQL_CURSOR_STATIC)")
+print("Type of cursor being used: ", end="")
+
+if cursorType == ibm_db.SQL_CURSOR_FORWARD_ONLY:
+    print("Forward only (SQL_CURSOR_FORWARD_ONLY)\n")
+elif cursorType == ibm_db.SQL_CURSOR_KEYSET_DRIVEN:
+    print("Keyset driven (SQL_CURSOR_KEYSET_DRIVEN)\n")
+elif cursorType == ibm_db.SQL_CURSOR_DYNAMIC:
+    print("Dynamic (SQL_CURSOR_DYNAMIC)\n")
+elif cursorType == ibm_db.SQL_CURSOR_STATIC:
+    print("Static (SQL_CURSOR_STATIC)\n")
+else:
+    print("Unknown\n")
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT * FROM employee WHERE edlevel > 17" ... Done!
+
+Obtaining information about the type of cursor being used ... Done!
+
+Type of cursor specified : Static (SQL_CURSOR_STATIC)
+Type of cursor being used: Static (SQL_CURSOR_STATIC)
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-next_result.html b/python_samples/HTML_Documentation/ibm_db-next_result.html new file mode 100644 index 0000000..f7a1532 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-next_result.html @@ -0,0 +1,13535 @@ + + + + +ibm_db-next_result + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.next_result()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve the next result set returned by a stored procedure.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.next_result( IBM_DBStatementstatement)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object that contains multiple result sets.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, a new IBM_DBStatement object that contains the next result set returned by a stored procedure — provided another result set was available.
  • +
  • If unsuccessful, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.next_result() API is used to retrieve the next result set that is returned by a stored procedure — provided the stored procedure returns more than one result set. (A stored procedure can return zero or more result sets.)

+

While data in the first result set returned by a stored procedure can be retrieved the same way data in a result set produced by a simple SELECT statement can be retrieved, data in subsequent result sets returned cannot be accessed until the ibm_db.next_result() API is used to copy the next result set to a uniquely named Python variable.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-next_result.py                                                             #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.next_result() API.   #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.callproc()                                                            #
+#                 ibm_db.fetch_tuple()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+spName = "HIGH_EARNERS"
+returnCode = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Used To Create A New Stored Procedure That
+# Returns Three Result Sets
+sqlStatement = "CREATE OR REPLACE PROCEDURE " + spName + " "
+sqlStatement += "LANGUAGE SQL "
+sqlStatement += "DYNAMIC RESULT SETS 3 "
+sqlStatement += "READS SQL DATA "
+sqlStatement += "NO EXTERNAL ACTION "
+sqlStatement += "BEGIN "
+sqlStatement += "  DECLARE avgSalary INT DEFAULT 0; "
+sqlStatement += "  DECLARE c1 CURSOR WITH RETURN FOR "
+sqlStatement += "    SELECT firstnme, lastname, salary, job FROM employee "
+sqlStatement += "    WHERE job = 'DESIGNER' AND "
+sqlStatement += "    salary > avgSalary "
+sqlStatement += "    ORDER BY salary DESC; "
+sqlStatement += "  DECLARE c2 CURSOR WITH RETURN FOR "
+sqlStatement += "    SELECT firstnme, lastname, salary, job FROM employee "
+sqlStatement += "    WHERE job = 'ANALYST' AND "
+sqlStatement += "    salary > avgSalary "
+sqlStatement += "    ORDER BY salary DESC; "
+sqlStatement += "  DECLARE c3 CURSOR WITH RETURN FOR "
+sqlStatement += "    SELECT firstnme, lastname, salary, job FROM employee "
+sqlStatement += "    WHERE job = 'SALESREP' AND "
+sqlStatement += "    salary > avgSalary "
+sqlStatement += "    ORDER BY salary DESC; "
+sqlStatement += "  SELECT INT(AVG(salary)) INTO avgSalary FROM employee; "
+sqlStatement += "  OPEN c1; "
+sqlStatement += "  OPEN c2; "
+sqlStatement += "  OPEN c3; "
+sqlStatement += "END"
+
+# Execute The SQL Statement Just Defined
+print("Creating an SQL stored procedure named \"" + spName + "\" ... ", end="")
+try:
+    returnCode = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Execute The Stored Procedure Just Created
+resultSet_1 = None
+print("Executing the " + spName + " procedure & retrieving the first ", end="")
+print("result set produced ... ", end="")
+try:
+    resultSet_1 = ibm_db.callproc(dbConnection, spName)
+except Exception:
+    pass
+
+# If The Stored Procedure Specified Could Not Be Executed, Display An Error Message And Exit 
+if resultSet_1 is None:
+    print("\nERROR: Unable to execute the stored procedure specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message; Then Format And Display The Data Values Returned
+else:
+    print("Done!\n")
+
+# Retrieve The Second Result Set From The Stored Procedure Just Executed
+print("Retrieving the second result set produced by the " + spName, end="")
+print(" procedure ... ", end="")
+resultSet_2 = False
+try:
+    resultSet_2 = ibm_db.next_result(resultSet_1)
+except Exception:
+    pass
+
+# If The Second Result Set Could Not Be Retrieved, Display An Error Message And Exit 
+if resultSet_2 is False:
+    print("\nERROR: Unable to retrieve the second result set returned by the stored procedure.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")  
+
+# Retrieve The Third Result Set From The Stored Procedure Just Executed
+print("Retrieving the third result set produced by the " + spName, end="")
+print(" procedure ... ", end="")
+resultSet_3 = False
+try:
+    resultSet_3 = ibm_db.next_result(resultSet_1)
+except Exception:
+    pass
+
+# If The Third Result Set Could Not Be Retrieved, Display An Error Message And Exit 
+if resultSet_3 is False:
+    print("\nERROR: Unable to retrieve the third result set returned by the stored procedure.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Information retrieved:")
+
+# As Long As There Are Records To Retrieve, ... 
+noData = False
+loopCounter = 1
+printHeader = True
+dataRecord = True
+while noData is False:
+
+    # Display Record Header Information
+    if printHeader is True:
+        print("\n  Result set " + str(loopCounter) + " details:\n")
+        print("  FIRSTNME        LASTNAME            SALARY      JOB")
+        print("  ______________  __________________  __________  ________")
+        printHeader = False
+
+    # Retrieve A Record From The Appropriate Result Set And Store It In A Python Tuple
+    if loopCounter is 1:
+        try:
+            dataRecord = ibm_db.fetch_tuple(resultSet_1)
+        except:
+            pass
+    elif loopCounter is 2:
+        try:
+            dataRecord = ibm_db.fetch_tuple(resultSet_2)
+        except:
+            pass
+    elif loopCounter is 3:
+        try:
+            dataRecord = ibm_db.fetch_tuple(resultSet_3)
+        except:
+            pass
+
+    # If The Record Could Not Be Retrieved Or If There Was No Data To Retrieve, Increment The
+    # Loop Counter Variable And Set The Appropriate Variables To True 
+    if dataRecord is False:
+        loopCounter += 1
+        printHeader = True
+        dataRecord = True
+        
+        # If There Is No More Data To Retrieve, Set The "No Data" Flag And Exit The Loop  
+        if loopCounter is 4:
+            noData = True
+        else:
+            continue
+        
+    # Otherwise, Extract And Display The Information Stored In The Data Record Retrieved
+    else:
+        print("  {:<14}" .format(dataRecord[0]), end="")
+        print("  {:<18}" .format(dataRecord[1]), end="")
+        print("  ${:>9}" .format(dataRecord[2]), end="")
+        print("  {:<10}" .format(dataRecord[3]))
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Creating an SQL stored procedure named "HIGH_EARNERS" ... Done!
+
+Executing the HIGH_EARNERS procedure & retrieving the first result set produced ... Done!
+
+Retrieving the second result set produced by the HIGH_EARNERS procedure ... Done!
+
+Retrieving the third result set produced by the HIGH_EARNERS procedure ... Done!
+
+Information retrieved:
+
+  Result set 1 details:
+
+  FIRSTNME        LASTNAME            SALARY      JOB
+  ______________  __________________  __________  ________
+  REBA            JOHN                $ 69840.00  DESIGNER  
+  WILLIAM         JONES               $ 68270.00  DESIGNER  
+  KIYOSHI         YAMAMOTO            $ 64680.00  DESIGNER  
+  ELIZABETH       PIANKA              $ 62250.00  DESIGNER  
+
+  Result set 2 details:
+
+  FIRSTNME        LASTNAME            SALARY      JOB
+  ______________  __________________  __________  ________
+  DELORES         QUINTANA            $ 73800.00  ANALYST   
+  HEATHER         NICHOLLS            $ 68420.00  ANALYST   
+  KIM             NATZ                $ 68420.00  ANALYST   
+
+  Result set 3 details:
+
+  FIRSTNME        LASTNAME            SALARY      JOB
+  ______________  __________________  __________  ________
+  VINCENZO        LUCCHESSI           $ 66500.00  SALESREP  
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-num_fields.html b/python_samples/HTML_Documentation/ibm_db-num_fields.html new file mode 100644 index 0000000..5eba126 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-num_fields.html @@ -0,0 +1,13384 @@ + + + + +ibm_db-num_fields + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.num_fields()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Determine the number of columns that exist in a result set.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

int ibm_db.num_fields( IBM_DBStatementstatement)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object that contains a result set.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an integer representing the number of columns (fields) that exist in the result associated with the IBM_DBStatement object specified.
  • +
  • If unsuccessful or if the IBM_DBStatement object specified is not valid, the value False.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.num_fields() API is used to determine the number of columns that exist in a result set. Having this information can be useful when retrieving and processing result sets that were produced by dynamically generated queries, or were returned by stored procedures.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-num_fields.py                                                              #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db-num_fields() API.    #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+numColumns = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT * FROM project WHERE prstaff < 5"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed
+print("Examining the result set produced ... ", end="")
+try:
+    numColumns = ibm_db.num_fields(resultSet)
+except Exception:
+    pass
+ 
+# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error
+# Message And Exit 
+if numColumns is False:
+    print("\nERROR: Unable to obtain information about the result set produced.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display The Information Retrieved
+print("There are " + str(numColumns) + " columns in the result set produced by the query.\n")
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT * FROM project WHERE prstaff < 5" ... Done!
+
+Examining the result set produced ... Done!
+
+There are 8 columns in the result set produced by the query.
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-num_rows.html b/python_samples/HTML_Documentation/ibm_db-num_rows.html new file mode 100644 index 0000000..ceb1d4d --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-num_rows.html @@ -0,0 +1,13443 @@ + + + + +ibm_db-num_rows + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.num_rows()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Determine how many rows were inserted, updated, or deleted by an SQL statement.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

int ibm_db.num_rows( IBM_DBStatementstatement)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object associated with an INSERT, UPDATE, or DELETE SQL statement.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an integer representing the number of rows that were affected by the last SQL operation performed using the IBM_DBStatement object specified.
  • +
  • If unsuccessful, nothing.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.num_rows() API is used to return the number of rows that were affected by an INSERT, UPDATE, or DELETE operation. And, in some cases, it can be used to indicate how many rows will be returned by a SELECT statement. (For example, if the ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH statement option is turned ON or a scrollable cursor is used.)

+

It is important to note that the overhead associated with scrollable cursors can significantly degrade application performance. So, if the only reason you would use a scrollable cursor would be to determine how many rows could be returned by a SELECT statement, you would be better off using a forward-only cursor and issuing a "SELECT COUNT(*)" statement (with the same predicates as your intended SELECT statement) and retrieving the value returned.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-num_rows.py                                                                #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db-num_rows() API.      #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.autocommit()                                                          #
+#                 ibm_db.prepare()                                                             #
+#                 ibm_db.exec_many()                                                           #
+#                 ibm_db.exec_rollback()                                                       #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+returnCode = False
+preparedStmt = False
+numRows = False
+resultSet = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+    
+# Turn Autocommit Behavior OFF
+print("Turning AUTOCOMMIT behavior OFF ... ", end="")
+returnCode = ibm_db.autocommit(dbConnection, 0)
+if returnCode is False:
+    print("\nERROR: Unable to turn off AUTOCOMMIT behavior.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+    
+# Define The INSERT Statement (With Parameter Markers) That Is To Be Used To Add Data
+# To The DEPARTMENT Table
+sqlStatement = "INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)"
+
+# Prepare The SQL Statement Just Defined
+print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit
+if preparedStmt is False:
+    print("\nERROR: Unable to prepare the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Create A List Of Data Values That Are To Be Supplied For The Parameter Markers Coded
+# In The INSERT Statement Specified
+pmValues = (('K22', 'SALES', '000110'), 
+            ('L22', 'FINANCE', '000120'), 
+            ('M22', 'HUMAN RESOURCES', '000130'))
+
+# Execute The SQL Statement Just Prepared
+print("Executing the prepared SQL statement ... ", end="")
+try:
+    returnCode = ibm_db.execute_many(preparedStmt, pmValues) 
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message And Display The Number Of Records Added
+else:
+    print("Done!\n")
+
+# Find Out How Many Rows Were Affected By The INSERT Operation
+try:
+    numRows = ibm_db.num_rows(preparedStmt)
+except Exception:
+    pass
+ 
+# If Information About The Number Rows Affected Could Not Be Obtained, Display An Error
+# Message And Exit 
+if numRows is False:
+    print("\nERROR: Unable to obtain information about the number of rows affected.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Display The Information Obtained
+else:
+    print("Number of rows affected by the INSERT operation: " + str(numRows) + "\n")
+
+# Back Out The Changes Just Made To The Database
+print("Backing out changes made to the database ... ", end="")
+try:
+    resultSet = ibm_db.rollback(dbConnection)
+except Exception:
+    pass
+
+# If The Rollback Operation Could Not Be Performed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to roll back the previous operation.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+    
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Turning AUTOCOMMIT behavior OFF ... Done!
+
+Preparing the SQL statement "INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)" ... Done!
+
+Executing the prepared SQL statement ... Done!
+
+Number of rows affected by the INSERT operation: 3
+
+Backing out changes made to the database ... Done!
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-pconnect.html b/python_samples/HTML_Documentation/ibm_db-pconnect.html new file mode 100644 index 0000000..3ef8516 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-pconnect.html @@ -0,0 +1,13745 @@ + + + + +ibm_db-pconnect + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.pconnect()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Establish a persistent connection to an IBM Db2 server or database.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBConnection ibm_db.pconnect( stringconnectionInfo,stringuserID,stringuserPassword[, dictionaryoptions] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connectionInfo    : A valid Db2 database alias (if the database has been cataloged in the system database directory) or a connection string with the format DRIVER={IBM DB2 ODBC DRIVER};ATTACH=connType;DATABASE=dbName;HOSTNAME=hostName;PORT=port;PROTOCOL=TCPIP;UID=userName;PWD=password where:

    +
      +
    • connType     : Specifies whether the connection is to be made to a Db2 server or database; TRUE indicates the connection is to be made to a Db2 server and FALSE indicates the connection is to be made to a database.
    • +
    • dbName         : The name of the Db2 server or database the connection is to be made to. This option is only required when connecting to a Db2 database.
    • +
    • hostName     : The host name or IP address of the Db2 server the connection is to be made to. (The hostname is the name of the Db2 server, as it is known to the TCP/IP network.) This option is only required when connecting to a Db2 server.
    • +
    • port             : The port number that receives Db2 connections on the server the connection is to be made to. (Port number 50000 is used by default.) This option is only required when connecting to a Db2 server.
    • +
    • userName     : The user name/ID that is to be used for authentication when the connection is established.
    • +
    • password     : The password that corresponds to the user name/ID specified in the userName parameter.

    • +
    +
  • +
  • userID                   : The user ID that is to be used for authentication when a connection is established. If a Db2 database alias is NOT provided in the connectionInfo parameter, this parameter must contain an empty string.

    +
  • +
  • userPassword      : The password that corresponds to the user ID specified in the userPassword parameter. If a Db2 database alias is NOT provided in the connectionInfo parameter, this parameter must contain an empty string.
  • +
  • options                 : A dictionary containing key-value pairs for the attributes that are to be set before a connection is established. Valid keys for IBM_DBConnection objects are:

    +
      +
    • ibm_db.SQL_ATTR_AUTOCOMMIT                     : Specifies whether AUTOCOMMIT mode is to be used or not; ibm_db.SQL_AUTOCOMMIT_ON will turn AUTOCOMMIT behavior ON and ibm_db.SQL_AUTOCOMMIT_OFF will turn it OFF.
    • +
    • ibm_db.SQL_ATTR_CASE                                 : The case that column names will be returned in; ibm_db.CASE_NATURAL will cause column names to be returned in natural case, ibm_db.CASE_LOWER will cause them to be returned in lower case, and ibm_db.CASE_UPPER will cause them to be returned in upper case. (This attribute can only be used with Db2 databases on OS/390 or z/OS servers.)
    • +
    • ibm_db.SQL_ATTR_CURRENT_SCHEMA             : The name of the schema to use, by default, when performing operations that require a schema name and one is not provided.
    • +
    • ibm_db.SQL_ATTR_USE_TRUSTED_CONTEXT   : Specifies whether the connection to a Db2 server or database is to be treated as a trusted connection; ibm_db.SQL_TRUE indicates the connection can be trusted and ibm_db.SQL_FALSE indicates the connection should not to be treated as a trusted connection.

    • +
    +
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, a valid IBM_DBConnection object.
  • +
  • If unsuccessful, the value None.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.pconnect() API is used to establish a persistent connection to an IBM Db2 server or database.

+

Unlike connections that are established using the ibm_db.connect() API, persistent connections created with the ibm_db.pconnect() API are not closed with the ibm_db.close() API. Instead, they are returned to a process-wide connection pool (when the ibm_db.close() API is executed.) Then, the next time the ibm_db.pconnect() API is called, the connection pool is searched for a matching connection and if one is found, it is returned to the application — new connections are not created unless there is no connection in the pool that meets the application's needs.

+

As with the ibm_db.connect() API, if a connection to a remote Db2 server or database is desired, the information needed to connect to the server (i.e., the host name, port number, and communications protocol) must be provided before a connection to either resource can be established. If a connection to a local, cataloged Db2 database is needed instead, just the alias for the database, as defined in the system database directory, must be supplied; values for the userID and userPassword parameters are optional. (If this API is called and just a local database alias is provided — for example, conn = ibm_db.connect( 'SAMPLE', ' ', ' ' ), — an attempt to establish a connection to the database will be made using the authorization ID and password for the current logged in Db2 instance user.)

+ +
+
+
+
+
+
+

Examples:

+
+
+
+
+
+
+

  Example 1: Create a pool of 10 local Db2 database connections

+ +
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-pconnect_DB.py                                                             #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.pconnect() API to    #
+#            create a pool of connections to a local Db2 database.                             #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.num_rows()                                                            #
+#                 ibm_db.close()                                                               #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"        # The Alias For The Cataloged, Local Database
+userID = "db2inst1"      # The Instance User ID At The Local Server
+passWord = "Passw0rd"    # The Password For The Instance User ID At The Local Server
+dbConnection = list(range(10))
+resultSet = False
+returnCode = False
+
+# Construct The String That Will Be Used To Establish A Db2 Database Connection
+connString = "ATTACH=FALSE"              # Attach To A Database; Not A Server
+connString += ";DATABASE=" + dbName      # Required To Connect To A Database     
+connString += ";PROTOCOL=TCPIP"
+connString += ";UID=" + userID
+connString += ";PWD=" + passWord
+
+# Display A Status Message Indicating An Attempt To Establish Ten Connections To A Db2 
+# Database Is About To Be Made
+print("\nEstablishing 10 connections to the \'" + dbName + "\' database ... \n")
+
+# Establish Ten Connections To The Local Db2 Database Specified
+for loopCounter in range(10):
+
+    # Attempt To Establish A Database Connection 
+    try:
+        dbConnection[loopCounter] = ibm_db.pconnect(connString, '', '')
+    except Exception:
+        pass
+
+    # If A Connection Could Not Be Established, Display An Error Message And Continue
+    if dbConnection[loopCounter] is None:
+        print("\nERROR: Unable to connect to the \'" + dbName + "\' database.")
+        continue
+
+    # Otherwise, Display A "Connection Ready" Status Message
+    else:
+        print("  Connection {:>2} ready!" .format(loopCounter + 1))
+
+# Add A Blank Line To The End Of The List Of Connections Created
+print()
+
+# Retrieve Data From The Database Using Connection Number Five
+if not dbConnection[5] is None:
+
+    # Define The SQL Statement That Is To Be Executed 
+    sqlStatement = "SELECT * FROM department"
+
+    # Set The Statement Option That Is To be Used When the Statement Is Executed
+    stmtOption = {ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON}
+
+    # Execute The SQL Statement Just Defined (Using The Desired Option)
+    print("Executing the SQL statement \"" + sqlStatement + "\" from Connection 5 ... ", end="")
+    currentConnection = dbConnection[5]
+    try:
+        resultSet = ibm_db.exec_immediate(currentConnection, sqlStatement, stmtOption)
+    except Exception:
+        pass
+
+    # If The SQL Statement Could Not Be Executed, Display An Error Message And Continue
+    if resultSet is False:
+        print("\nERROR: Unable to execute the SQL statement specified.\n")
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!\n")
+
+    # Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Just
+    # Executed (There Should Be 14 Rows)
+    try:
+        numRows = ibm_db.num_rows(resultSet)
+    except Exception:
+        pass
+ 
+    # Display An Appropriate Message, Based On The Information Returned
+    if numRows <= 0:
+        print("Unable to obtain information about the number of rows returned.\n")
+    else:
+        print("Number of rows returned by the query: " + str(numRows) + "\n")
+
+    # Attempt To Close The Database Connection (Connection 5)
+    print("Closing database Connection 5 ... ", end="")
+    try:
+        returnCode = ibm_db.close(currentConnection)
+    except Exception:
+        pass
+
+    # If The Connection Was Not Closed, Display An Error Message
+    if returnCode is False:
+        print("\nERROR: Unable to disconnect from the " + dbName + " database.")
+        
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!")
+        print("(Connection 5 has been returned the pool of connections opened earlier.)\n")
+
+# Display A Status Message Indicating An Attempt To Close The Remaining Db2 Database 
+# Connections Is About To Be Made
+print("Closing all remaining connections to the \'" + dbName + "\' database ... \n")
+
+# Attempt To Close All Of The Db2 Database Connections That Were Opened Earlier
+for loopCounter in range(10):
+    
+    # If The Specified Connection Is Open, Attempt To Close It
+    if not dbConnection[loopCounter] is None:
+        try:
+            returnCode = ibm_db.close(dbConnection[loopCounter])
+        except Exception:
+            pass
+
+        # If The Connection Could Not Be Closed, Display An Error Message And Continue
+        if returnCode is False:
+            print("\nERROR: Unable to disconnect from the " + dbName + " database.")
+            continue
+
+        # Otherwise, Display A "Connection Closed" Status Message
+        else:
+            print("  Connection {:>2} closed!" .format(loopCounter + 1))
+
+# Display A Status Message Indicating All Database Connections Have Been Returned To The
+# Connection Pool
+print("\nAll database connections have been returned the pool of connections opened earlier.\n")
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Establishing 10 connections to the 'SAMPLE' database ... 
+
+  Connection  1 ready!
+  Connection  2 ready!
+  Connection  3 ready!
+  Connection  4 ready!
+  Connection  5 ready!
+  Connection  6 ready!
+  Connection  7 ready!
+  Connection  8 ready!
+  Connection  9 ready!
+  Connection 10 ready!
+
+Executing the SQL statement "SELECT * FROM department" from Connection 5 ... Done!
+
+Number of rows returned by the query: 14
+
+Closing database Connection 5 ... Done!
+(Connection 5 has been returned the pool of connections opened earlier.)
+
+Closing all remaining connections to the 'SAMPLE' database ... 
+
+  Connection  1 closed!
+  Connection  2 closed!
+  Connection  3 closed!
+  Connection  4 closed!
+  Connection  5 closed!
+  Connection  6 closed!
+  Connection  7 closed!
+  Connection  8 closed!
+  Connection  9 closed!
+  Connection 10 closed!
+
+All database connections have been returned the pool of connections opened earlier.
+
+
+
+
+ +
+
+ +
+
+
+
+

  Restart the Jupyter Notebook to clear the Db2 connection pool

+ +
(This must be done before the second example can run)
+ +
+
+
+
+
+
In [ ]:
+
+
+
import os
+os._exit(0)
+
+ +
+
+
+ +
+
+
+
+

  Example 2: Create a pool of 10 remote Db2 server connections

+ +
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-pconnect_SERVER.py                                                         #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.pconnect() API to    #
+#            create a pool of connections to a remote Db2 server.                              #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.createdbNX()                                                          #
+#                 ibm_db.close()                                                               #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+hostName = "197.126.80.22"    # IP Address Of Remote Server
+portNum = "50000"             # Port Number That Receives Db2 Connections On The Remote Server 
+userID = "db2inst2"           # The Instance User ID At The Remote Server
+passWord = "ibmdb2"           # The Password For The Instance User ID At The Remote Server
+svrConnection = list(range(10))
+dbName = "MY_DB"
+returnCode = None
+
+# Construct The String That Will Be Used To Establish A Db2 Server Connection
+connString = "DRIVER={IBM DB2 ODBC DRIVER}"
+connString += ";ATTACH=TRUE"             # Attach To A Server; Not A Database
+connString += ";DATABASE="               # Ignored When Connecting To A Server
+connString += ";HOSTNAME=" + hostName    # Required To Connect To A Server
+connString += ";PORT=" + portNum         # Required To Connect To A Server
+connString += ";PROTOCOL=TCPIP"          # Required To Connect To A Server
+connString += ";UID=" + userID
+connString += ";PWD=" + passWord
+
+# Display A Status Message Indicating An Attempt To Establish Ten Connections To A Remote 
+# Db2 Server Is About To Be Made
+print("\nEstablishing 10 connections to the \'" + hostName + "\' server ... \n")
+
+# Establish Ten Connections To The Db2 Server Specified
+for loopCounter in range(10):
+
+    # Attempt To Establish A Db2 Server Connection 
+    try:
+        svrConnection[loopCounter] = ibm_db.pconnect(connString, '', '')
+    except Exception:
+        pass
+
+    # If A Connection Could Not Be Established, Display An Error Message And Continue
+    if svrConnection[loopCounter] is None:
+        print("\nERROR: Unable to connect to the \'" + hostName + "\' server.")
+        continue
+
+    # Otherwise, Display A "Connection Ready" Status Message
+    else:
+        print("  Connection {:>2} ready!" .format(loopCounter + 1))
+
+# Add A Blank Line To The End Of The List Of Connections Created
+print()
+
+# Attempt To Create A New Database At The Remote Server Using Connection Number Five
+if not svrConnection[5] is None:
+    print("Creating a database named " + dbName + " using Connection 5.  Please wait.")
+    try:
+        returnCode = ibm_db.createdbNX(svrConnection[5], dbName)
+    except Exception:
+        pass
+
+    # If The Database Could Not Be Created, Display An Error Message And Exit 
+    if returnCode is None:
+        print("ERROR: Unable to create the " + dbName + " database.\n")
+        errorMsg = ibm_db.conn_errormsg(svrConnection[5])
+        print(errorMsg + "\n")
+
+    # Otherwise, Display A Status Message Indicating The Database Was Created 
+    else:
+        print("\nThe database \"" + dbName + "\" has been created!\n")
+
+    # Attempt To Close The Db2 Server Connection (Connection 5)
+    print("Closing Db2 server Connection 5 ... ", end="")
+    try:
+        returnCode = ibm_db.close(svrConnection[5])
+    except Exception:
+        pass
+
+    # If The Connection Was Not Closed, Display An Error Message
+    if returnCode is False:
+        print("\nERROR: Unable to disconnect from the " + hostName + " server.")
+        
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!")
+        print("(Connection 5 has been returned the pool of connections opened earlier.)\n")
+
+# Display A Status Message Indicating An Attempt To Close The Remaining Db2 Server
+# Connections Is About To Be Made
+print("Closing all remaining connections to the \'" + hostName + "\' server ... \n")
+
+# Attempt To Close All Of The Remaining Db2 Server Connections That Were Opened Earlier
+for loopCounter in range(10):
+    
+    # If The Specified Connection Is Open, Attempt To Close It
+    if not svrConnection[loopCounter] is None:
+        try:
+            returnCode = ibm_db.close(svrConnection[loopCounter])
+        except Exception:
+            pass
+
+        # If The Connection Could Not Be Closed, Display An Error Message And Continue
+        if returnCode is False:
+            print("\nERROR: Unable to disconnect from the " + hostName + " server.")
+            continue
+
+        # Otherwise, Display A "Connection Closed" Status Message
+        else:
+            print("  Connection {:>2} closed!" .format(loopCounter + 1))
+
+# Display A Status Message Indicating All Db2 Server Connections Have Been Returned To The
+# Connection Pool
+print("\nAll Db2 server connections have been returned the pool of connections opened earlier.\n")
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Establishing 10 connections to the '197.126.80.22' server ... 
+
+  Connection  1 ready!
+  Connection  2 ready!
+  Connection  3 ready!
+  Connection  4 ready!
+  Connection  5 ready!
+  Connection  6 ready!
+  Connection  7 ready!
+  Connection  8 ready!
+  Connection  9 ready!
+  Connection 10 ready!
+
+Creating a database named MY_DB using Connection 5.  Please wait.
+
+The database "MY_DB" has been created!
+
+Closing Db2 server Connection 5 ... Done!
+(Connection 5 has been returned the pool of connections opened earlier.)
+
+Closing all remaining connections to the '197.126.80.22' server ... 
+
+  Connection  1 closed!
+  Connection  2 closed!
+  Connection  3 closed!
+  Connection  4 closed!
+  Connection  5 closed!
+  Connection  6 closed!
+  Connection  7 closed!
+  Connection  8 closed!
+  Connection  9 closed!
+  Connection 10 closed!
+
+All Db2 server connections have been returned the pool of connections opened earlier.
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-prepare.html b/python_samples/HTML_Documentation/ibm_db-prepare.html new file mode 100644 index 0000000..aa8f41d --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-prepare.html @@ -0,0 +1,13426 @@ + + + + +ibm_db-prepare + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.prepare()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Send an SQL statement to a Db2 server or database to have it prepared for execution.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.prepare( IBM_DBConnectionconnection,stringSQLstatement[, dictionaryoptions] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection        : A valid Db2 server or database connection.
  • +
  • SQLstatement   : A valid, executable SQL statement (that may or may not contain one or more parameter markers).
  • +
  • options              : A dictionary containing key-value pairs for the statement attributes that are to be set when the statement provided in the SQLstatement parameter is prepared. Valid keys and values are:

    +
      +
    • ibm_db.SQL_ATTR_CURSOR_TYPE                             : Specifies the type of cursor that is to be used for processing result sets. Valid values are:
        +
      • ibm_db.SQL_CURSOR_FORWARD_ONLY                 : A forward only cursor should be used (i.e., a cursor that only scrolls forward).
      • +
      • ibm_db. SQL_CURSOR_KEYSET_DRIVEN             : A keyset-driven cursor should be used.
      • +
      • ibm_db.SQL_CURSOR_STATIC                             : A static cursor should be used.
      • +
      • ibm_db.SQL_CURSOR_DYNAMIC                           : A dynamic, scrollable cursor that detects all changes to the result set, should be used. Dynamic cursors are only supported by Db2 for z/OS servers.
      • +
      +
    • +
    • ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH                 : Enables Db2 to determine the number of rows that are returned by a query (so the entire result set can be prefetched into memory, when possible); ibm_db.SQL_ROWCOUNT_PREFETCH_ON will turn this behavior ON and ibm_db.SQL_ROWCOUNT_PREFETCH_OFF will turn it OFF.
    • +
    • ibm_db.SQL_ATTR_QUERY_TIMEOUT                         : The number of seconds to wait for an SQL statement to execute before aborting and returning to the application. This option can be used to terminate long running queries — the default value of 0 means an application will wait indefinitely for the server to complete execution.

    • +
    +
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, a valid IBM_DBStatement object.
  • +
  • If unsuccessful, the value None.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.prepare() API is used to send an SQL statement to a Db2 server or database to have it prepared for execution — once an SQL statement has been prepared, it can be submitted for execution multiple times without having to be re-prepared. This benefits applications in two ways:

+
    +
  • Improved performance: when an SQL statement is prepared, the database server creates an optimized access plan for executing that statement. Subsequent executions of the prepared statement (using the ibm_db.execute() or ibm_db.execute_many() API) will reuse that access plan, eliminating the overhead of dynamically creating new access plans each time the statement is executed.

    +
  • +
  • Greater flexibility: when an SQL statement is prepared, literal values hard-coded in the statement can be replaced with parameter markers — depicted by question mark (?) characters. An SQL statement can contain zero or more parameter markers, each representing a variable or value that is to be provided at run time. Values for parameter markers can be supplied via variables (using the ibm_db.bind_param() API), or for input parameters only, in a tuple (if the ibm_db.execute() API is used) or a tuple of tuples (if the ibm_db.execute_many() API is used). Regardless of which method used, when the prepared statement is executed, the database server will check each input value supplied to ensure the appropriate data type is used.

    +
  • +
+

It is important to note that parameter markers are only allowed in certain places in an SQL statement. For example, they cannot be used to represent one or more columns in the result set reurned by a SELECT statement, nor can they be used as the operand of a binary operator like the equal sign (=).

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-prepare.py                                                                 #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.prepare() API.       #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.execute()                                                             #
+#                 ibm_db.fetch_assoc()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+preparedStmt = False
+returnCode = False
+dataRecord = None
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT lastname, firstnme FROM employee WHERE job = 'PRES'"
+
+# Prepare The SQL Statement Just Defined
+print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit
+if preparedStmt is False:
+    print("\nERROR: Unable to prepare the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Execute The SQL Statement Just Prepared
+print("Executing the prepared SQL statement ... ", end="")
+try:
+    returnCode = ibm_db.execute(preparedStmt)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Retrieve The Data Produced By The SQL Statement And Store It In A Python Dictionary
+try:
+    dataRecord = ibm_db.fetch_assoc(preparedStmt)
+except:
+    pass
+
+# If The Data Could Not Be Retrieved, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to retrieve the data produced by the SQL statement.")
+    conn.closeConnection()
+    exit(-1)
+
+# If The Data Could be Retrieved, Display It
+else:
+    print("Query results:\n")
+    print("FIRSTNME    LASTNAME")
+    print("__________  ________")
+    print("{:10}  {:<24}\n" .format(dataRecord['FIRSTNME'], dataRecord['LASTNAME']))
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Preparing the SQL statement "SELECT lastname, firstnme FROM employee WHERE job = 'PRES'" ... Done!
+
+Executing the prepared SQL statement ... Done!
+
+Query results:
+
+FIRSTNME    LASTNAME
+__________  ________
+CHRISTINE   HAAS                    
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-primary_keys.html b/python_samples/HTML_Documentation/ibm_db-primary_keys.html new file mode 100644 index 0000000..987495a --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-primary_keys.html @@ -0,0 +1,13417 @@ + + + + +ibm_db-primary_keys + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.primary_keys()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve information about the columns that make up the primary key for a table.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.primary_keys( IBM_DBConnectionconnection,stringqualifierName,stringschemaName,stringtableName)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection        : A valid Db2 server or database connection.
  • +
  • qualifierName    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value None or an empty string ('') for Db2 databases on other operating systems.
  • +
  • schemaName     : The name of the schema that contains the table(s) that primary key information is to be obtained for. To use the schema associated with the current connection, provide the value None.
  • +
  • tableName          : The name of the table(s) that primary key information is to be obtained for.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an IBM_DBStatement with a result set that contains the following information:

    +
      +
    • PK_NAME            : The name of the primary key.
    • +
    • TABLE_CAT        : The name of the catalog associated with the schema and table that contains the primary key; Db2 does not use catalogs so this field will always contain the value None. (Db2 databases on OS/390 or z/OS servers can return information in this field.)
    • +
    • TABLE_SCHEM    : The name of the schema for the table that contains the primary key.
    • +
    • TABLE_NAME      : The name of the table that contains the primary key.
    • +
    • COLUMN_NAME    : The name of a primary key column.
    • +
    • KEY_SEQ            : The COLUMN_NAME column's ordinal position in the primary key, starting from 1.

    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.primary_keys() API is used to retrieve information about the columns that make up the primary key for a table (if one has been defined).

+

The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-primary_keys.py                                                            #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.primary_keys() API.  #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.fetch_assoc()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+schemaName = userID.upper()
+tableName = "PROJECT"
+resultSet = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Retrieve Information About All Primary Keys That Have Been Defined For The
+# Table Specified
+print("Obtaining information about primary keys created for ", end="")
+print("the " + schemaName + "." + tableName + " table ... ", end="")
+try:
+    resultSet = ibm_db.primary_keys(dbConnection, None, schemaName, tableName)
+except Exception:
+    pass
+
+# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit
+if resultSet is False:
+    print("\nERROR: Unable to obtain the information desired\n.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# As Long As There Are Records (That Were Produced By The ibm_db.primary_keys API), ...
+noData = False
+loopCounter = 1
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop  
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Information Retrieved
+    else:
+
+        # Display Record Header Information
+        print("Primary key " + str(loopCounter) + " details:")
+        print("______________________________________")
+
+        # Display The Information Stored In The Data Record Retrieved
+        print("Primary key table schema  : {}" .format(dataRecord['TABLE_SCHEM']))
+        print("Primary key table name    : {}" .format(dataRecord['TABLE_NAME']))
+        print("Primary key column name   : {}" .format(dataRecord['COLUMN_NAME']))
+        print("Primary key column number : {}" .format(dataRecord['KEY_SEQ']))
+        print("Primary key name          : {}" .format(dataRecord['PK_NAME']))
+
+        # Increment The loopCounter Variable And Print A Blank Line To Separate The
+        # Records From Each Other
+        loopCounter += 1
+        print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Obtaining information about primary keys created for the DB2INST1.PROJECT table ... Done!
+
+Primary key 1 details:
+______________________________________
+Primary key table schema  : DB2INST1
+Primary key table name    : PROJECT
+Primary key column name   : PROJNO
+Primary key column number : 1
+Primary key name          : PK_PROJECT
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-procedure_columns.html b/python_samples/HTML_Documentation/ibm_db-procedure_columns.html new file mode 100644 index 0000000..58befb1 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-procedure_columns.html @@ -0,0 +1,13542 @@ + + + + +ibm_db-procedure_columns + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.procedure_columns()

+
+
+
+
+
+
+

Pupose:

+
+
+
+
+
+
+

Retrieve information about the parameters that have been defined for one or more procedures.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.procedure_columns( IBM_DBConnectionconnection,
stringqualifierName,stringschemaName,stringprocedureName,stringparameterName)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection          : A valid Db2 server or database connection.
  • +
  • qualifierName      : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value None or an empty string ('') for Db2 databases on other operating systems.
  • +
  • schemaName       : The name of the schema that contains the procedure(s) that parameter information is to be obtained for. To match all schemas, provide the value None or an empty string; to match select schemas, provide a search pattern that contains _ and/or % wildcards.
  • +
  • procedureName   : The name of the procedure(s) that parameter information is to be obtained for. To match all procedures, provide the value None or an empty string; to match select procedures, provide a search pattern that contains _ and/or % wildcards.
  • +
  • parameterName    : The name of the parameter(s) that information is to be obtained for. To match all parameters, provide the value None or an empty string; to match select parameters, provide a search pattern that contains _ and/or % wildcards.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an IBM_DBStatement with a result set that contains the following information:

    +
      +
    • PROCEDURE_CAT            : The name of the catalog associated with the schema that contains the procedure; Db2 does not use catalogs so this field will always contain the value None. (Db2 databases on OS/390 or z/OS servers can return information in this field.)
    • +
    • PROCEDURE_SCHEM        : The name of the schema that contains the procedure.
    • +
    • PROCEDURE_NAME          : The name of the procedure.
    • +
    • COLUMN_NAME                : The name of a parameter that has been defined for the procedure.
    • +
    • COLUMN_TYPE                : A value that indicates what type of parameter the parameter is. Valid values for this field are:

      +
        +
      • ibm_db.SQL_PARAM_INPUT                 : The parameter is an input (IN) parameter.
      • +
      • ibm_db.SQL_PARAM_OUTPUT               : The parameter is an output (OUT) parameter.
      • +
      • ibm_db.SQL_PARAM_INPUT_OUTPUT   : The parameter is an input/output (INOUT) parameter.

      • +
      +
    • +
    • DATA_TYPE                    : An integer value that represents the SQL data type of the parameter. On Linux and UNIX systems, valid values for this field can be found in the file /opt/ibm/db2/V11.1/include/sqlcli.h.

      +
    • +
    • TYPE_NAME                    : The data source-specific string representation of the SQL data type of the parameter.
    • +
    • COLUMN_SIZE                : The maximum number of bytes needed to display the parameter's data as a string.
    • +
    • BUFFER_LENGTH            : The maximum number of bytes needed to store the parameter's data in an application variable.
    • +
    • DECIMAL_DIGITS          : The scale (i.e., total number of significant digits to the right of the decimal point) of the parameter - provided the parameter has a numerical data type. If the parameter does not have a numerical data type, this field will contain the value None.
    • +
    • NUM_PREC_RADIX          : A numerical value that indicates whether the parameter's data type represents an exact numeric data type (10) or an approximate numeric data type (2). If the parameter does not have a numerical data type, this field will contain the value None.
    • +
    • NULLABLE                      : Indication of whether the parameter accepts a NULL value; ibm_db.SQL_YES will be returned if NULL values are accepted and ibm_db.SQL_NO will be returned if they are not..
    • +
    • REMARKS                        : A user-supplied description of the parameter (if one has been provided).
    • +
    • COLUMN_DEF                  : The default value for the parameter (if one has been defined).
    • +
    • SQL_DATA_TYPE            : An integer value that represents the SQL data type of the parameter, as it would appear in a row descriptor record. On Linux and UNIX systems, valid values for this field can be found in the file /opt/ibm/db2/V11.1/include/sqlcli.h. (In most cases, this will be the same as the value provided in the DATA_TYPE field.)
    • +
    • SQL_DATETIME_SUB      : An integer value that represents the SQL date/time subtype code for the parameter - provided the parameter has a date, time, or timestamp data type. If the parameter does not have one of these data types, this field will contain the value None. (On Linux and UNIX systems, valid values for this field can be found in the file /opt/ibm/db2/V11.1/include/sqlcli.h.)
    • +
    • CHAR_OCTET_LENGTH    : The maximum length, in octets (8-bit bytes), needed to display the parameter's data as a string. (This will be the same as the COLUMN_SIZE value for single-byte character set data.) If the parameter does not have a character data type, this field will contain the value None.
    • +
    • ORDINAL_POSITION      : The parameter's ordinal position in the CALL statement that would be used to invoke the procedure, starting from 1.
    • +
    • IS_NULLABLE                : Indication of whether the parameter can contain NULL values, according to the rules in the ISO SQL92 standard. This field will contain the value "YES" if the column can contain NULL values and the value "NO" if it cannot.

    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.procedure_columns() API is used to retrieve information about the parameters that have been defined for one or more stored procedures.

+

The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-procedure_columns.py                                                       #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.procedure_columns()  #
+#            API.                                                                              #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.fetch_assoc()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+procedureName = 'VALIDATE_LENGTH'
+resultSet = False
+dataRecord = False
+sqlDataTypes = {0 : "SQL_UNKNOWN_TYPE", 1 : "SQL_CHAR", 2 : "SQL_NUMERIC", 3 : "SQL_DECIMAL",
+    4 : "SQL_INTEGER", 5 : "SQL_SMALLINT", 6 : "SQL_FLOAT", 7 : "SQL_REAL", 8 : "SQL_DOUBLE",
+    9 : "SQL_DATETIME", 12 : "SQL_VARCHAR", 16 : "SQL_BOOLEAN", 19 : "SQL_ROW", 
+    91 : "SQL_TYPE_DATE", 92 : "SQL_TYPE_TIME", 93 : "SQL_TYPE_TIMESTAMP",
+    95 : "SQL_TYPE_TIMESTAMP_WITH_TIMEZONE", -8 : "SQL_WCHAR", -9 : "SQL_WVARCHAR",
+    -10 : "SQL_WLONGVARCHAR", -95 : "SQL_GRAPHIC", -96 : "SQL_VARGRAPHIC",
+    -97 : "SQL_LONGVARGRAPHIC", -98 : "SQL_BLOB", -99 : "SQL_CLOB", -350 : "SQL_DBCLOB",
+    -360 : "SQL_DECFLOAT", -370 : "SQL_XML", -380 : "SQL_CURSORHANDLE", -400 : "SQL_DATALINK",
+    -450 : "SQL_USER_DEFINED_TYPE"}
+sqlDateTimeSubtypes = {1 : "SQL_CODE_DATE", 2 : "SQL_CODE_TIME", 3 : "SQL_CODE_TIMESTAMP",
+    4 : "SQL_CODE_TIMESTAMP_WITH_TIMEZONE"}
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Retrieve Information About The Parameters That Have Been Defined For A Particular
+# Stored Procedure
+print("Obtaining information about the parameters that have been defined for the ", end="")
+print(procedureName + "\nprocedure ... ", end="")
+try:
+    resultSet = ibm_db.procedure_columns(dbConnection, None, '', procedureName, None)
+except Exception:
+    pass
+
+# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit
+if resultSet is False:
+    print("\nERROR: Unable to obtain the information desired\n.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# As Long As There Are Records (That Were Produced By The ibm_db.procedure_columns API), ...
+noData = False
+loopCounter = 1
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop  
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Information Retrieved
+    else:
+
+        # Display Record Header Information
+        print("Stored procedure parameter " + str(loopCounter) + " details:")
+        print("____________________________________________________________")
+
+        # Display The Information Stored In The Data Record Retrieved
+        print("Procedure schema                   : {}" .format(dataRecord['PROCEDURE_SCHEM']))
+        print("Procedure name                     : {}" .format(dataRecord['PROCEDURE_NAME']))
+        print("Parameter name                     : {}" .format(dataRecord['COLUMN_NAME']))
+        print("Parameter type                     : ", end="")
+        if dataRecord['COLUMN_TYPE'] == ibm_db.SQL_PARAM_INPUT:
+            print("Input (IN)")
+        elif dataRecord['COLUMN_TYPE'] == ibm_db.SQL_PARAM_INPUT_OUTPUT:
+            print("Input/output (INOUT)")
+        elif dataRecord['COLUMN_TYPE'] == ibm_db.SQL_PARAM_OUTPUT:
+            print("Output (OUT)")
+        else:
+            print("Unknown")
+        print("Data type                          : {}" .format(dataRecord['TYPE_NAME']))
+        print("Size                               : {}" .format(dataRecord['COLUMN_SIZE']))
+        print("Buffer size                        : {}" .format(dataRecord['BUFFER_LENGTH']))
+        print("Scale (decimal digits)             : ", end="")
+        if dataRecord['DECIMAL_DIGITS'] == None:
+            print("Not applicable")
+        else:
+            print("{}" .format(dataRecord['DECIMAL_DIGITS']))
+        print("Precision radix                    : ", end="")
+        if dataRecord['NUM_PREC_RADIX'] == 10:
+            print("Exact numeric data type")
+        elif dataRecord['NUM_PREC_RADIX'] == 2:
+            print("Approximate numeric data type")
+        elif dataRecord['NUM_PREC_RADIX'] == None:
+            print("Not applicable")
+        print("Can accept NULL values             : ", end="")
+        if dataRecord['NULLABLE'] == 1:
+            print("YES")
+        else:
+            print("NO")
+        print("Remarks                            : {}" .format(dataRecord['REMARKS']))
+        print("Default value                      : {}" .format(dataRecord['COLUMN_DEF']))
+        print("SQL data type                      : ", end="")
+        print(sqlDataTypes.get(dataRecord['SQL_DATA_TYPE']))
+        print("SQL data/time subtype              : ", end="")
+        print(sqlDateTimeSubtypes.get(dataRecord['SQL_DATETIME_SUB']))
+        print("Length in octets                   : ", end="")
+        if dataRecord['CHAR_OCTET_LENGTH'] == None:
+            print("Not applicable")
+        else:
+            print("{}" .format(dataRecord['CHAR_OCTET_LENGTH']))
+        print("Ordinal position                   : {}" .format(dataRecord['ORDINAL_POSITION']))
+        print("Can accept or return \'None\' values : {}" .format(dataRecord['IS_NULLABLE']))
+
+        # Increment The loopCounter Variable And Print A Blank Line To Separate The
+        # Records From Each Other
+        loopCounter += 1
+        print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Obtaining information about the parameters that have been defined for the VALIDATE_LENGTH
+procedure ... Done!
+
+Stored procedure parameter 1 details:
+____________________________________________________________
+Procedure schema                   : SYSIBMADM
+Procedure name                     : VALIDATE_LENGTH
+Parameter name                     : LENGTH1
+Parameter type                     : Input (IN)
+Data type                          : INTEGER
+Size                               : 10
+Buffer size                        : 4
+Scale (decimal digits)             : 0
+Precision radix                    : Exact numeric data type
+Can accept NULL values             : YES
+Remarks                            : None
+Default value                      : None
+SQL data type                      : SQL_INTEGER
+SQL data/time subtype              : None
+Length in octets                   : Not applicable
+Ordinal position                   : 1
+Can accept or return 'None' values : YES
+
+Stored procedure parameter 2 details:
+____________________________________________________________
+Procedure schema                   : SYSIBMADM
+Procedure name                     : VALIDATE_LENGTH
+Parameter name                     : LENGTH2
+Parameter type                     : Input (IN)
+Data type                          : INTEGER
+Size                               : 10
+Buffer size                        : 4
+Scale (decimal digits)             : 0
+Precision radix                    : Exact numeric data type
+Can accept NULL values             : YES
+Remarks                            : None
+Default value                      : None
+SQL data type                      : SQL_INTEGER
+SQL data/time subtype              : None
+Length in octets                   : Not applicable
+Ordinal position                   : 2
+Can accept or return 'None' values : YES
+
+Stored procedure parameter 3 details:
+____________________________________________________________
+Procedure schema                   : SYSIBMADM
+Procedure name                     : VALIDATE_LENGTH
+Parameter name                     : ERRORCODE
+Parameter type                     : Input (IN)
+Data type                          : VARCHAR
+Size                               : 10
+Buffer size                        : 10
+Scale (decimal digits)             : Not applicable
+Precision radix                    : Not applicable
+Can accept NULL values             : YES
+Remarks                            : None
+Default value                      : None
+SQL data type                      : SQL_VARCHAR
+SQL data/time subtype              : None
+Length in octets                   : 10
+Ordinal position                   : 3
+Can accept or return 'None' values : YES
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-procedures.html b/python_samples/HTML_Documentation/ibm_db-procedures.html new file mode 100644 index 0000000..cc996cd --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-procedures.html @@ -0,0 +1,13438 @@ + + + + +ibm_db-procedures + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.procedures()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve a list of procedures that have been registered in a database.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.procedures( IBM_DBConnectionconnection,stringqualifierName,stringschemaName,stringprocedureName)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection          : A valid Db2 server or database connection.
  • +
  • qualifierName      : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value None or an empty string ('') for Db2 databases on other operating systems.
  • +
  • schemaName       : The name of the schema that contains the procedure(s) that information is to be obtained for. To match all schemas, provide the value None or an empty string; to match select schemas, provide a search pattern that contains _ and/or % wildcards.
  • +
  • procedureName   : The name of the procedure(s) that information is to be obtained for. To match all procedures, provide the value None or an empty string; to match select procedures, provide a search pattern that contains _ and/or % wildcards.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an IBM_DBStatement with a result set that contains the following information:

    +
      +
    • PROCEDURE_CAT          : The name of the catalog associated with the schema that contains the procedure; Db2 does not use catalogs so this field will always contain the value None. (Db2 databases on OS/390 or z/OS servers can return information in this field.)
    • +
    • PROCEDURE_SCHEM      : The name of the schema that contains the procedure.
    • +
    • PROCEDURE_NAME        : The name of the procedure.
    • +
    • NUM_INPUT_PARAMS    : The number of input (IN) parameters that have been defined for the procedure.
    • +
    • NUM_OUTPUT_PARAMS  : The number of output (OUT) parameters that have been defined for the procedure.
    • +
    • NUM_RESULT_SETS      : The number of result sets the procedure will return.
    • +
    • REMARKS                      : A user-supplied description of the procedure (if one has been provided).
    • +
    • PROCEDURE_TYPE        : A numerical value that indicates whether the procedure is a stored procedure that does not return a value (1) or a function that returns a value (2). This field will always contain the value 1.

    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.procedures() API is used to retrieve a list of stored procedures that have been registered in a database.

+

The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-procedures.py                                                              #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.procedures() API.    #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.fetch_assoc()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+schemaName = userID.upper()
+resultSet = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Retrieve Information About Stored Procedures That Have Been Defined In The
+# Current User's Schema
+print("Obtaining information about stored procedures in the ", end="")
+print(schemaName + " schema ... ", end="")
+try:
+    resultSet = ibm_db.procedures(dbConnection, None, schemaName, '')
+except Exception:
+    pass
+
+# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit
+if resultSet is False:
+    print("\nERROR: Unable to obtain the information desired\n.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# As Long As There Are Records (That Were Produced By The ibm_db.procedures API), ...
+noData = False
+loopCounter = 1
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop  
+    if dataRecord is False:
+        noData = True
+        
+    # Otherwise, Display The Information Retrieved
+    else:
+
+        # Display Record Header Information
+        print("Stored procedure " + str(loopCounter) + " details:")
+        print("_______________________________________________")
+
+        # Display The Information Stored In The Data Record Retrieved
+        print("Procedure schema               : {}" .format(dataRecord['PROCEDURE_SCHEM']))
+        print("Procedure name                 : {}" .format(dataRecord['PROCEDURE_NAME']))
+        print("Number of input parameters     : {}" .format(dataRecord['NUM_INPUT_PARAMS']))
+        print("Number of output parameters    : {}" .format(dataRecord['NUM_OUTPUT_PARAMS']))
+        print("Number of result sets produced : {}" .format(dataRecord['NUM_RESULT_SETS']))
+        print("Procedure comments             : {}" .format(dataRecord['REMARKS']))
+
+        # Increment The loopCounter Variable And Print A Blank Line To Separate The
+        # Records From Each Other
+        loopCounter += 1
+        print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Obtaining information about stored procedures in the DB2INST1 schema ... Done!
+
+Stored procedure 1 details:
+_______________________________________________
+Procedure schema               : DB2INST1
+Procedure name                 : BONUS_INCREASE
+Number of input parameters     : 0
+Number of output parameters    : 0
+Number of result sets produced : 1
+Procedure comments             : None
+
+Stored procedure 2 details:
+_______________________________________________
+Procedure schema               : DB2INST1
+Procedure name                 : HIGH_EARNERS
+Number of input parameters     : 0
+Number of output parameters    : 0
+Number of result sets produced : 3
+Procedure comments             : None
+
+Stored procedure 3 details:
+_______________________________________________
+Procedure schema               : DB2INST1
+Procedure name                 : SALARY_STATS
+Number of input parameters     : 0
+Number of output parameters    : 0
+Number of result sets produced : 0
+Procedure comments             : None
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-recreatedb.html b/python_samples/HTML_Documentation/ibm_db-recreatedb.html new file mode 100644 index 0000000..78f22d5 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-recreatedb.html @@ -0,0 +1,13512 @@ + + + + +ibm_db-recreatedb + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.recreatedb()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Drop and recreate a database, using the name and code set specified.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.recreatedb( IBM_DBConnectionconnection,stringdbName[, stringcodeSet] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server connection.
  • +
  • dbName         : The name of the database that is to be dropped and recreated.
  • +
  • codeSet         : The code set that is to be used for storing data that is entered into the database after it has been dropped and recreated. If a codeSet value is not specified, the UTF-8 (Unicode) code set is used.
  • +
+ +
+
+
+
+
+
+

Return Value:

+
+
+
+
+
+
+
    +
  • True      : The database specified was dropped and recreated.
  • +
  • False    : The database specified could not be dropped and recreated.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.recreatedb() API is used to delete (drop) an existing database, and then recreate it; the code set that is to be used for storing data entered into the database can also be changed when this API is executed. (The code set controls how unique numbers are assigned to characters in a particular character set.)

+ +
+
+
+
+
+
+

Examples:

+
+
+
+
+
+
+

  Example 1: Drop and recreate a database stored on a local server

+ +
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-recreatedb_LOCAL.py                                                        #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.recreatedb() API to  #
+#            drop and recreate a local Db2 database.                                           #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.conn_errormsg()                                                       #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+userID = "db2inst1"           # User ID (Recognized By The Local Server)
+passWord = "Passw0rd"         # User Password
+svrConnection = None
+dbName = "MY_DB"
+returnCode = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To The Local Db2 Server
+conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    svrConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Drop And Recreate A Database At The Local Server
+print("Dropping and recreating a database named " + dbName + ". Please wait.")
+try:
+    returnCode = ibm_db.recreatedb(svrConnection, dbName, 'UTF-8')
+except Exception:
+    pass
+
+# If The Database Could Not Be Recreated, Display An Error Message And Exit 
+if returnCode is None:
+    print("ERROR: Unable to drop and recreate the " + dbName + " database.\n")
+    errorMsg = ibm_db.conn_errormsg(svrConnection)
+    print(errorMsg + "\n")
+    conn.closeConnection()
+    exit(-1)
+    
+# Otherwise, Display A Status Message 
+else:
+    print("\nThe database \"" + dbName + "\" has been created!\n")
+    #    query_sdb_dir(dbName)
+
+# Close The Db2 Server Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the local server ... Done!
+
+Dropping and recreating a database named MY_DB. Please wait.
+
+The database "MY_DB" has been created!
+
+Disconnecting from the local server ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
+

  Example 2: Drop and recreate a database stored on a remote server

+ +
+
+
+
+
+
In [2]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-recreatedb_REMOTE.py                                                       #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.recreatedb() API to  #
+#            drop and recreate a database on a remote Db2 server.                              #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.conn_errormsg()                                                       #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+hostName = "197.126.80.22"    # IP Address Of A Remote Server
+portNum = "50000"             # Port Number Used By Db2
+userID = "db2inst2"           # User ID (Recognized By The Remote Server)
+passWord = "ibmdb2"           # User Password
+svrConnection = None
+dbName = "MY_DB"
+returnCode = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Remote Db2 Server
+conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    svrConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Delete (Drop) And Recreate A Database At The Remote Server
+print("Dropping and recreating a database named " + dbName + " ", end="")
+print("at the " + hostName + " server. Please wait.")
+try:
+    returnCode = ibm_db.recreatedb(svrConnection, dbName, 'UTF-8')
+except Exception:
+    pass
+
+# If The Database Could Not Be Recreated, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to drop and recreate the " + dbName + " database.\n")
+    errorMsg = ibm_db.conn_errormsg(svrConnection)
+    print(errorMsg + "\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Display A Status Message And Verify That Information About The Database
+# That Was Just Recreated Exists In The Db2 System Database Directory
+else:
+    print("\nThe database \"" + dbName + "\" has been recreated!\n")
+
+# Close The Db2 Server Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the 197.126.80.22 server ... Done!
+
+Dropping and recreating a database named MY_DB at the 197.126.80.22 server. Please wait.
+
+The database "MY_DB" has been recreated!
+
+Disconnecting from the 197.126.80.22 server ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-result.html b/python_samples/HTML_Documentation/ibm_db-result.html new file mode 100644 index 0000000..dc8fe32 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-result.html @@ -0,0 +1,13385 @@ + + + + +ibm_db-result + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.result()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve a value from a column in the current row of a result set.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

mixed ibm_db.result( IBM_DBStatementstatement,mixedcolumn)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object that contains a result set.
  • +
  • column        : The zero-indexed position of the column or the name of the column in the result set that data is to be retrieved from.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, the value for the column specified, in the current row of the result set.
  • +
  • If unsuccessful or if the column specified doesn't exist, the value None.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.result() API is used to retrieve a value from a column in the current row of a result set. This function is used in conjunction with the ibm_db.fetch_row() API, which is used to advance a cursor to the next row or move a cursor to a specific row in a result set. Once the cursor has been moved, this API is then called to retrieve data for individual columns in the row.

+

As an alternative to using the ibm_db.fetch_row() and ibm_db.result() APIs to iterate through a result set and retrieve data values for individual columns, applications can use the ibm_db.fetch_tuple(), ibm_db.fetch_assoc(), or ibm_db.fetch_both() API to position the cursor in a result set and retrieve the data for a complete row, in a single operation.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-result.py                                                                  #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.fetch_row() API.     #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.fetch_row()                                                           #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+resultSet = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT deptname FROM department WHERE admrdept = 'A00'"
+
+# Execute The SQL Statement Just Defined
+print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Query results:\n")
+print("DEPTNAME")
+print("____________________________")
+
+# As Long As There Are Records In The Result Set Produced, ...
+while (ibm_db.fetch_row(resultSet) is True):
+
+    # Display The Data Retrieved
+    print(ibm_db.result(resultSet, 0)) 
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement "SELECT deptname FROM department WHERE admrdept = 'A00'" ... Done!
+
+Query results:
+
+DEPTNAME
+____________________________
+SPIFFY COMPUTER SERVICE DIV.
+PLANNING
+INFORMATION CENTER
+DEVELOPMENT CENTER
+SUPPORT SERVICES
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-rollback.html b/python_samples/HTML_Documentation/ibm_db-rollback.html new file mode 100644 index 0000000..08bee7f --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-rollback.html @@ -0,0 +1,13434 @@ + + + + +ibm_db-rollback + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.rollback()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Terminate an in-progress transaction and back out (roll back) the effects of all operations performed by the transaction.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.rollback( IBM_DBConnectionconnection)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server or database connection.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • True      : Changes made by the current transaction were successfully backed out of the database (rolled back).
  • +
  • False    : Changes made by the current transaction could not be rolled back.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.rollback() API is used to terminate an in-progress transaction and back out (roll back) the effects of all operations that were performed by that transaction. (A transaction is a sequence of one or more SQL operations that are grouped together as a single process; when a transaction is rolled back, the database is returned to the sate it was in at the time the transaction was started.) Normally, a transaction is initiated the first time an SQL statement is executed after a database connection is established or an in-progress transaction ends. But, with Python applications, each SQL operation is treated as a transaction that is implicitly committed (made permanent) as soon as it completes unless AUTOCOMMIT behavior is turned OFF. Consequently, the ibm_db.rollback() API has no effect when AUTOCOMMIT behavior is ON (the default).

+

It is important to note that if the connection being used is a persistent connection (i.e., a connection that was established with the ibm_db.pconnect() API), in-progress transactions for all applications using the connection will be rolled back when this API is called. For this reason, the use of persistent connections is not recommended for applications that need to control transaction boundaries.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-rollback.py                                                                #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.rollback() API.      #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.autocommit()                                                          #
+#                 ibm_db.exec_immediate()                                                      #
+#                 ibm_db.stmt_errormsg()                                                       #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The get_row_count() Function That Has Been Defined In The File Named                  #
+# "ibm_db_tools.py";  This Function Contains The Programming Logic Needed To Obtain And        #
+# Display The Number Of Rows (Records) Found In A Db2 Database Table                           #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import get_row_count
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+returnCode = False
+resultSet = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Turn Autocommit Behavior OFF
+print("Turning AUTOCOMMIT behavior OFF ... ", end="")
+try:
+    returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_OFF)
+except Exception:
+    pass
+
+# If AUTOCOMMIT Behavior Could Not Be Turned OFF, Display An Error Message And Continue
+if returnCode is False:
+    print("\nERROR: Unable to turn AUTOCOMMIT behavior OFF.")
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table
+returnCode = get_row_count(dbConnection, 'DEPARTMENT')
+if returnCode is False:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The INSERT Statement That Is To Be Used To Add Data To The DEPARTMENT Table
+sqlStatement = "INSERT INTO department VALUES('K01', 'SALES', '000130', 'K01', NULL)"
+
+# Execute The SQL Statement Just Defined
+print("Inserting a record into the DEPARTMENT table ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the INSERT statement specified.")
+    errorMsg = ibm_db.stmt_errormsg()
+    print("\n" + errorMsg + "\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display The Number Of Rows That Exist In The DEPARTMENT Table Now
+# (The Number Returned Should Change)
+returnCode = get_row_count(dbConnection, 'DEPARTMENT')
+if returnCode is False:
+    conn.closeConnection()
+    exit(-1)
+
+# Back Out The Changes Just Made To The Database
+print("Backing out changes made to the database ... ", end="")
+resultSet = False
+try:
+    resultSet = ibm_db.rollback(dbConnection)
+except Exception:
+    pass
+
+# If The Roll Back Operation Could Not Be Performed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to roll back the previous operation.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display The Number Of Rows That Exist In The DEPARTMENT Table Now
+# (The Number Should Revert Back To The Original Value)
+returnCode = get_row_count(dbConnection, 'DEPARTMENT')
+if returnCode is False:
+    conn.closeConnection()
+    exit(-1)
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Turning AUTOCOMMIT behavior OFF ... Done!
+
+Number of records found in the DEPARTMENT table: 14
+
+Inserting a record into the DEPARTMENT table ... Done!
+
+Number of records found in the DEPARTMENT table: 15
+
+Backing out changes made to the database ... Done!
+
+Number of records found in the DEPARTMENT table: 14
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-server_info.html b/python_samples/HTML_Documentation/ibm_db-server_info.html new file mode 100644 index 0000000..75f1b9f --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-server_info.html @@ -0,0 +1,13563 @@ + + + + +ibm_db-server_info + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.server_info()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Obtain information about an IBM Db2 server.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

PyTypeObject ibm_db.server_info( IBM_DBConnectionconnection)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection    : A valid Db2 server connection.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, a PyTypeObject populated with the following information:

    +
      +
    • DBMS_NAME                         : The name of the Db2 server the application is connected to, in the form of a string that begins with the letters "DB2/" and is followed by the name of the operating system being used. For example, "DB2/LINUXX8664" indicates Db2 is running on a 64-bit Linux for x86 processor server.
    • +
    • DBMS_VER                           : The version of the Db2 software running on the server, in the form of a string that has the format VV.RR.MMFF, where VV is the major version, RR is the release number, MM is the modification number, and FF is the fix pack number. For example, "11.01.0404" represents version 11, release 1, modification 4, fix pack 4.
    • +
    • DB_CODEPAGE                     : The default code page that is used by the server.
    • +
    • DB_NAME                             : The name of the database the application is connected to, if any.
    • +
    • DFT_ISOLATION                 : The default transaction isolation level that is used by the server. Valid values are:

      +
        +
      • RR     : Repeatable read. (Data affected by a pending transaction is not available to other transactions.)
      • +
      • RS     : Read stability. (Concurrently running transactions can add or remove rows that do not match the search condition of a pending transaction.)
      • +
      • CS     : Cursor stability. (Concurrently running transactions cannot update or delete the row a pending transaction currently holds.)
      • +
      • UR     : Uncommitted read. (Changes made by concurrently running transactions are immediately visible.)
      • +
      • NC     : No commit. (Changes are visible at the end of a successful operation; explicit commits and rollbacks are not allowed.)

      • +
      +
    • +
    • IDENTIFIER_QUOTE_CHAR  : The character that is used as an identifier delimiter.

      +
    • +
    • INST_NAME                           : The name of the Db2 instance at the server.
    • +
    • ISOLATION_OPTION             : A list of the reansaction isolation levels that are supported by the connected server, stored in a tuple. Valid values are the same as those listed under DFT_ISOLATION.
    • +
    • KEYWORDS                             : A list of the keywords that are reserved by the server, stored in a tuple.
    • +
    • LIKE_ESCAPE_CLAUSE         : A boolean value indicating whether the database server supports the use of % and _ as wildcard characters (True) or not (False).
    • +
    • MAX_COL_NAME_LEN             : Maximum length a column name can be, expressed in bytes.
    • +
    • MAX_IDENTIFIER_LEN         : Maximum length an SQL identifier can be, expressed in characters.
    • +
    • MAX_INDEX_SIZE                 : Maximum amount of data (from combined columns) that can be used in an index, expressed in bytes.
    • +
    • MAX_PROC_NAME_LEN           : Maximum length a stored procedure name can be, expressed in bytes.
    • +
    • MAX_ROW_SIZE                     : Maximum length a row in a base table can be, expressed in bytes.
    • +
    • MAX_SCHEMA_NAME_LEN      : Maximum length a schema name can be, expressed in bytes.
    • +
    • MAX_STATEMENT_LEN          : Maximum length an SQL statement can be, expressed in bytes.
    • +
    • MAX_TABLE_NAME_LEN        : Maximum length a table name can be, expressed in bytes.
    • +
    • NON_NULLABLE_COLUMNS    : A boolean value indicating whether the database server supports the ability to define columns that are NOT NULL (True) or not (False).
    • +
    • PROCEDURES                        : A boolean value indicating whether the database server supports the use of the CALL statement to invoke stored procedures (True) or not (False).
    • +
    • SPECIAL_CHARS                  : A string containing all characters other than A-Z, 0-9, and underscore (_) that can be used in an identifier name.
    • +
    • SQL_CONFORMANCE              : The level of conformance to the ANSI/ISO SQL-92 specification that is offered by the database server. Valid values are:

        +
      • ENTRY                : Entry-level SQL-92 compliance is provided.
      • +
      • FIPS127            : FIPS-127-2 transitional compliance is provided.
      • +
      • FULL                  : Full level SQL-92 compliance is provided.
      • +
      • INTERMEDIATE  : Intermediate level SQL-92 compliance is provided.

      • +
      +
    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.server_info() API is used to obtain detailed information about an IBM Db2 database server.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-server_info.py                                                             #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.server_info() API.   #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+svrConnection = None
+serverInfo = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server
+conn = Db2ConnectionMgr('SERVER', '', '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    svrConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Obtain Information About The Db2 Server Being Used
+print("Obtaining information about the server ... ", end="")
+try:
+    serverInfo = ibm_db.server_info(svrConnection)
+except Exception:
+    pass
+
+# If Information About The Server Could Not Be Obtained, Display An Error Message 
+if serverInfo is False:
+    print("\nERROR: Unable to obtain server information.\n")
+
+# Otherwise, Complete The Status Message; Then Format And Display The Data Retrieved
+else:
+    print("Done!\n")
+
+    # Display A Report Header
+    print("Server details:")
+    print("_____________________________________________________________________________")
+    
+    # Display The Server Data
+    print("Db2 database server name                 : {}" .format(serverInfo.DBMS_NAME))
+    print("Db2 software version                     : {}" .format(serverInfo.DBMS_VER))
+    print("Db2 instance name                        : {}" .format(serverInfo.INST_NAME))
+    print("Database codepage used                   : {}" .format(serverInfo.DB_CODEPAGE))
+    print("Database name                            : {}" .format(serverInfo.DB_NAME))
+
+    print("Isolation levels supported               : ", end="")
+    for loopCounter in range(0, len(serverInfo.ISOLATION_OPTION)):
+        if serverInfo.ISOLATION_OPTION[loopCounter] == 'UR':
+            print("Uncommitted Read (UR)", end="")
+        elif serverInfo.ISOLATION_OPTION[loopCounter] == 'CS':
+            print("Cursor Stability (CS)", end="")
+        elif serverInfo.ISOLATION_OPTION[loopCounter] == 'RS':
+            print("Read Stability (RS)", end="")
+        elif serverInfo.ISOLATION_OPTION[loopCounter] == 'RR':
+            print("Repeatable Read (RR)", end="")
+        elif serverInfo.ISOLATION_OPTION[loopCounter] == 'NC':
+            print("No Commit", end="")
+        if loopCounter < len(serverInfo.ISOLATION_OPTION) - 1:
+            print("\n" + " " * 43, end="")
+    print()
+
+    print("Default isolation level used             : ", end="")
+    if serverInfo.DFT_ISOLATION == 'NC':
+        print("No Commit")
+    else:
+        print("{}" .format(serverInfo.DFT_ISOLATION))
+
+    print("Identifier delimiter character           : ", end="")
+    print("{}" .format(serverInfo.IDENTIFIER_QUOTE_CHAR))
+
+    print("Use of % and _ as wildcards supported    : ", end="")
+    if serverInfo.LIKE_ESCAPE_CLAUSE == True:
+        print("Yes")
+    else:
+        print("No")
+
+    print("Maximum column name length               : ", end="")
+    print("{:<7} bytes" .format(serverInfo.MAX_COL_NAME_LEN))
+    print("Maximum SQL identifier length            : ", end="")
+    print("{:<7} characters" .format(serverInfo.MAX_IDENTIFIER_LEN))
+    print("Maximum index size (combined columns)    : ", end="")
+    print("{:<7} bytes" .format(serverInfo.MAX_INDEX_SIZE))
+    print("Maximum procedure name length            : ", end="")
+    print("{:<7} bytes" .format(serverInfo.MAX_PROC_NAME_LEN))
+    print("Maximum row size                         : ", end="")
+    print("{:<7} bytes" .format(serverInfo.MAX_ROW_SIZE))
+    print("Maximum schema name length               : ", end="")
+    print("{:<7} bytes" .format(serverInfo.MAX_SCHEMA_NAME_LEN))
+    print("Maximum SQL statement length             : ", end="")
+    print("{:<7} bytes" .format(serverInfo.MAX_STATEMENT_LEN))
+    print("Maximum table name length                : ", end="")
+    print("{:<7} bytes" .format(serverInfo.MAX_TABLE_NAME_LEN))
+
+    print("NOT NULL columns supported               : ", end="")
+    if serverInfo.NON_NULLABLE_COLUMNS == True:
+        print("Yes")
+    else:
+        print("No")
+    print("CALL statement supported                 : ", end="")
+    if serverInfo.PROCEDURES == True:
+        print("Yes")
+    else:
+        print("No")
+
+    print("Characters supported in identifier names : A-Z, 0-9, _, ", end="")
+    tempString = (", ".join(serverInfo.SPECIAL_CHARS))
+    endingPos = tempString.find(tempString[-1])
+    tempString = tempString[:int(endingPos)]
+    tempString += "and " + serverInfo.SPECIAL_CHARS[-1]
+    print(tempString)
+
+    print("ANSI/ISO SQL-92 conformance level        : ", end="")
+    if serverInfo.SQL_CONFORMANCE == 'ENTRY':
+        print("Entry-level compliance\n")
+    elif serverInfo.SQL_CONFORMANCE == 'INTERMEDIATE':
+        print("Intermediate-level compliance\n")
+    elif serverInfo.SQL_CONFORMANCE == 'FULL':
+        print("Full compliance\n")
+    elif serverInfo.SQL_CONFORMANCE == 'FIPS127':
+        print("FIPS-127-2 transitional compliance\n")
+
+    # Display Another Header, Followed By A Five-Column List Of Reserved Keywords
+    print("Reserved keywords:")
+    print('_' * 92 + "\n")
+    loopCounter = 0
+    while loopCounter < len(serverInfo.KEYWORDS):
+        colNumber = 0
+        while colNumber < 5:
+            print("{:<19}".format(serverInfo.KEYWORDS[loopCounter]), end="")
+            colNumber += 1
+            loopCounter += 1
+            if colNumber is 5:
+                print()
+            if loopCounter is len(serverInfo.KEYWORDS):
+                break
+
+# End The Last Row And Add A Blank Line To The End Of The Report
+print("\n")
+
+# Close The Server Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the ibm-UDOO-x86 server ... Done!
+
+Obtaining information about the server ... Done!
+
+Server details:
+_____________________________________________________________________________
+Db2 database server name                 : DB2/LINUXX8664
+Db2 software version                     : 11.01.0404
+Db2 instance name                        : DB2
+Database codepage used                   : 1208
+Database name                            :                   
+Isolation levels supported               : Uncommitted Read (UR)
+                                           Cursor Stability (CS)
+                                           Read Stability (RS)
+                                           Repeatable Read (RR)
+Default isolation level used             : CS
+Identifier delimiter character           : "
+Use of % and _ as wildcards supported    : Yes
+Maximum column name length               : 128     bytes
+Maximum SQL identifier length            : 128     characters
+Maximum index size (combined columns)    : 1024    bytes
+Maximum procedure name length            : 128     bytes
+Maximum row size                         : 32677   bytes
+Maximum schema name length               : 128     bytes
+Maximum SQL statement length             : 2097152 bytes
+Maximum table name length                : 128     bytes
+NOT NULL columns supported               : Yes
+CALL statement supported                 : Yes
+Characters supported in identifier names : A-Z, 0-9, _, @, and #
+ANSI/ISO SQL-92 conformance level        : FIPS-127-2 transitional compliance
+
+Reserved keywords:
+____________________________________________________________________________________________
+
+AFTER              ALIAS              ALLOW              APPLICATION        ASSOCIATE          
+ASUTIME            AUDIT              AUX                AUXILIARY          BEFORE             
+BINARY             BUFFERPOOL         CACHE              CALL               CALLED             
+CAPTURE            CARDINALITY        CCSID              CLUSTER            COLLECTION         
+COLLID             COMMENT            CONCAT             CONDITION          CONTAINS           
+COUNT_BIG          CURRENT_LC_CTYPE   CURRENT_PATH       CURRENT_SERVER     CURRENT_TIMEZONE   
+CYCLE              DATA               DATABASE           DAYS               DB2GENERAL         
+DB2GENRL           DB2SQL             DBINFO             DEFAULTS           DEFINITION         
+DETERMINISTIC      DISALLOW           DO                 DSNHATTR           DSSIZE             
+DYNAMIC            EACH               EDITPROC           ELSEIF             ENCODING           
+END-EXEC1          ERASE              EXCLUDING          EXIT               FENCED             
+FIELDPROC          FILE               FINAL              FREE               FUNCTION           
+GENERAL            GENERATED          GRAPHIC            HANDLER            HOLD               
+HOURS              IF                 INCLUDING          INCREMENT          INHERIT            
+INOUT              INTEGRITY          ISOBID             ITERATE            JAR                
+JAVA               LABEL              LC_CTYPE           LEAVE              LINKTYPE           
+LOCALE             LOCATOR            LOCATORS           LOCK               LOCKMAX            
+LOCKSIZE           LONG               LOOP               MAXVALUE           MICROSECOND        
+MICROSECONDS       MINUTES            MINVALUE           MODE               MODIFIES           
+MONTHS             NEW                NEW_TABLE          NOCACHE            NOCYCLE            
+NODENAME           NODENUMBER         NOMAXVALUE         NOMINVALUE         NOORDER            
+NULLS              NUMPARTS           OBID               OLD                OLD_TABLE          
+OPTIMIZATION       OPTIMIZE           OUT                OVERRIDING         PACKAGE            
+PARAMETER          PART               PARTITION          PATH               PIECESIZE          
+PLAN               PRIQTY             PROGRAM            PSID               QUERYNO            
+READS              RECOVERY           REFERENCING        RELEASE            RENAME             
+REPEAT             RESET              RESIGNAL           RESTART            RESULT             
+RESULT_SET_LOCATOR RETURN             RETURNS            ROUTINE            ROW                
+RRN                RUN                SAVEPOINT          SCRATCHPAD         SECONDS            
+SECQTY             SECURITY           SENSITIVE          SIGNAL             SIMPLE             
+SOURCE             SPECIFIC           SQLID              STANDARD           START              
+STATIC             STAY               STOGROUP           STORES             STYLE              
+SUBPAGES           SYNONYM            SYSFUN             SYSIBM             SYSPROC            
+SYSTEM             TABLESPACE         TRIGGER            TYPE               UNDO               
+UNTIL              VALIDPROC          VARIABLE           VARIANT            VCAT               
+VOLUMES            WHILE              WLM                YEARS              
+
+Disconnecting from the ibm-UDOO-x86 server ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-set_option.html b/python_samples/HTML_Documentation/ibm_db-set_option.html new file mode 100644 index 0000000..c82df5d --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-set_option.html @@ -0,0 +1,13732 @@ + + + + +ibm_db-set_option + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.set_option()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Assign a value to a connection or statement option (attribute).

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

bool ibm_db.set_option( mixedresource,dictionaryoptions,intresourceType)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • resource            : A valid IBM_DBConnection or IBM_DBStatement object.
  • +
  • options              : A dictionary containing key-value pairs for the attributes that are to be set. Valid keys for IBM_DBConnection objects are:

    +
      +
    • ibm_db.SQL_ATTR_AUTOCOMMIT                               : Specifies whether AUTOCOMMIT mode is to be used or not; ibm_db.SQL_AUTOCOMMIT_ON will turn AUTOCOMMIT behavior ON and ibm_db.SQL_AUTOCOMMIT_OFF will turn it OFF.
    • +
    • ibm_db.SQL_ATTR_CASE                                           : The case that column names will be returned in; ibm_db.CASE_NATURAL will cause column names to be returned in natural case, ibm_db.CASE_LOWER will cause them to be returned in lower case, and ibm_db.CASE_UPPER will cause them to be returned in upper case. (This attribute can only be used with Db2 databases on OS/390 or z/OS servers.)
    • +
    • ibm_db.SQL_ATTR_CURRENT_SCHEMA                       : The name of the schema to use, by default, when performing operations that require a schema name and one is not provided.
    • +
    • ibm_db.SQL_ATTR_INFO_ACCTSTR                           : A null-terminated user-defined string, up to 255 characters in length, that contains the client accounting string that is to be sent to the currently connected Db2 server or database. This option can only be set after a connection has been established.
    • +
    • ibm_db.SQL_ATTR_INFO_APPLNAME                         : A null-terminated user-defined character string, up to 255 characters in length, that contains the client application name that is to be sent to the currently connected Db2 server or database. This option can only be set after a connection has been established.
    • +
    • ibm_db.SQL_ATTR_INFO_PROGRAMNAME                   : A null-terminated user-defined character string, up to 20 bytes in length, that is used to specify the name of the application running on the client. This option can only be set before a connection has been established.
    • +
    • ibm_db.SQL_ATTR_INFO_USERID                             : The client user ID (accounting user ID) that is to be sent to the currently connected Db2 server or database. This information is used for identification purposes only—not for authentication. This option can only be set after a connection has been established.
    • +
    • ibm_db.SQL_ATTR_INFO_WRKSTNNAME                     : A null-terminated user-defined string, up to 255 characters in length, that contains the client workstation name that is to be sent to the currently connected Db2 server or database. This option can only be set after a connection has been established.
    • +
    • ibm_db.SQL_ATTR_USE_TRUSTED_CONTEXT             : Specifies whether the connection to a Db2 server or database is to be treated as a trusted connection; ibm_db.SQL_TRUE indicates the connection can be trusted and ibm_db.SQL_FALSE indicates the connection should not to be treated as a trusted connection. This option can only be set before a connection has been established.
    • +
    • ibm_db.SQL_ATTR_TRUSTED_CONTEXT_USERID       : A user defined character string containing the client user ID (accounting user ID) that an existing trusted connection is to be switched to — Do not use this option to create a trusted connection! This option can only be set after a connection has been established.
    • +
    • ibm_db.SQL_ATTR_TRUSTED_CONTEXT_PASSWORD   : A user defined string containing the password for the user ID provided via the ibm_db.SQL_ATTR_TRUSTED_CONTEXT_USERID option. This option must be provided if the database server requires a password when switching users on an existing trusted connection. This option can only be set after a connection has been established.

    • +
    +

    Valid keys for IBM_DBStatement objects are:

    +
      +
    • ibm_db.SQL_ATTR_CURSOR_TYPE                             : Specifies the type of cursor that is to be used for processing result sets. Valid values are:
        +
      • ibm_db.SQL_CURSOR_FORWARD_ONLY                 : A forward only cursor should be used (i.e., a cursor that only scrolls forward).
      • +
      • ibm_db. SQL_CURSOR_KEYSET_DRIVEN             : A keyset-driven cursor should be used.
      • +
      • ibm_db.SQL_CURSOR_STATIC                             : A static cursor should be used.
      • +
      • ibm_db.SQL_CURSOR_DYNAMIC                           : A dynamic, scrollable cursor that detects all changes to the result set, should be used. Dynamic cursors are only supported by Db2 for z/OS servers.
      • +
      +
    • +
    • ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH                 : Enables Db2 to determine the number of rows that are returned by a query (so the entire result set can be prefetched into memory, when possible); ibm_db.SQL_ROWCOUNT_PREFETCH_ON will turn this behavior ON and ibm_db.SQL_ROWCOUNT_PREFETCH_OFF will turn it OFF.
    • +
    • ibm_db.SQL_ATTR_QUERY_TIMEOUT                         : The number of seconds to wait for an SQL statement to execute before aborting and returning to the application. This option can be used to terminate long running queries — the default value of 0 means an application will wait indefinitely for the server to complete execution.

    • +
    +
  • +
  • resourceType    : Identifies whether the value provided in the resource parameter is an IBM_DBConnection object or an IBM_DBStatement object. Valid values for this parameter are:

    +
      +
    • 0   : The resource parameter contains a valid IBM_DBStatement object.
    • +
    • 1   : The resource parameter contains a valid IBM_DBConnection object.
    • +
    +
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • True      : The connection or statement option(s) specified were set.
  • +
  • False    : The connection or statement option(s) specified were not set.
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.set_option() API is used to assign a value to a connection or statement option (attribute). Once set, an attribute's value remains in effect until it is changed by another call to this API or the IBM_DBConnection or IBM_DBStatement object used is deleted.

+

It is important to note that options cannot be set for result set resources.

+ +
+
+
+
+
+
+

Examples:

+
+
+
+
+
+
+

    Example 1: Set connection options

+ +
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-set_option_CONNECTION.py                                                   #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.set_option() API to  #
+#            assign values to some of the connection options available.                        #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.connect()                                                             #
+#                 ibm_db.get_option()                                                          #
+#                 ibm_db.close()                                                               #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+returnCode = False
+
+# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database
+# Is About To Be Made
+print("\nConnecting to the \'" + dbName + "\' database ... ", end="")
+
+# Construct The String That Will Be Used To Establish A Db2 Database Connection
+connString = "ATTACH=FALSE"              # Attach To A Database; Not A Server
+connString += ";DATABASE=" + dbName      # Required To Connect To A Database     
+connString += ";PROTOCOL=TCPIP"
+connString += ";UID=" + userID
+connString += ";PWD=" + passWord
+
+# Attempt To Establish A Connection To The Database Specified
+try:
+    dbConnection = ibm_db.connect(connString, '', '')
+except Exception:
+    pass
+
+# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit
+if dbConnection is None:
+    print("\nERROR: Unable to connect to the \'" + dbName + "\' database.")
+    print("Connection string used: " + connString + "\n")
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Create A Dictionary That Contains Values For The Connection Options That Can Only Be Set 
+# After A Database Connection Is Established
+connectOptions = {ibm_db.SQL_ATTR_INFO_ACCTSTR : 'RESANDERS@IBM', 
+    ibm_db.SQL_ATTR_INFO_APPLNAME : 'ibm_db-set_option.py',
+    ibm_db.SQL_ATTR_INFO_USERID : 'db2inst1',
+    ibm_db.SQL_ATTR_INFO_WRKSTNNAME : 'ibm_UDOO_X86'}
+
+# Attempt To Set The Connection Options Specified
+print("Assigning values to four different connection options ... ", end="")
+try:
+    returnCode = ibm_db.set_option(dbConnection, connectOptions, 1)
+except Exception:
+    pass
+
+# If The Connection Options Could Not Be Set, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to set the connection options specified.\n")
+    if not dbConnection is None:
+        ibm_db.close(dbConnection)
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Display A Report Header
+print("Connection option settings:\n")
+print("OPTION                    SETTING")
+print("________________________  ____________________")
+
+# Retrieve And Display The Accounting String That Was Defined For The Client
+value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_ACCTSTR, 1)
+print("SQL_ATTR_INFO_ACCTSTR     " + value)
+
+
+# Retrieve And Display The Application Name That Was Defined For The Client
+value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_APPLNAME, 1)
+print("SQL_ATTR_INFO_APPLNAME    " + value)
+
+# Retrieve And Display The User ID That Was Defined For The Client
+value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_USERID, 1)
+print("SQL_ATTR_INFO_USERID      " + value)
+
+# Retrieve And Display The Workstation Name That Was Defined For The Client
+value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_WRKSTNNAME, 1)
+print("SQL_ATTR_INFO_WRKSTNNAME  " + value)
+
+# Add A Blank Line To The End Of The Report
+print()
+
+# Attempt To Close The Db2 Database Connection That Was Opened Earlier
+if not dbConnection is None:
+    print("Disconnecting from the \'" + dbName + "\' database ... ", end="")
+    try:
+        returnCode = ibm_db.close(dbConnection)
+    except Exception:
+        pass
+
+    # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit
+    if returnCode is False:
+        print("\nERROR: Unable to disconnect from the " + dbName + " database.")
+        exit(-1)
+
+    # Otherwise, Complete The Status Message
+    else:
+        print("Done!\n")
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the 'SAMPLE' database ... Done!
+
+Assigning values to four different connection options ... Done!
+
+Connection option settings:
+
+OPTION                    SETTING
+________________________  ____________________
+SQL_ATTR_INFO_ACCTSTR     RESANDERS@IBM
+SQL_ATTR_INFO_APPLNAME    ibm_db-set_option.py
+SQL_ATTR_INFO_USERID      db2inst1
+SQL_ATTR_INFO_WRKSTNNAME  ibm_UDOO_X86
+
+Disconnecting from the 'SAMPLE' database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
+

    Example 2: Set statement options

+ +
+
+
+
+
+
In [2]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-set_option_STATEMENT.py                                                    #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.set_option() API to  #
+#            assign a value to one of the statement options available.                         #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.prepare()                                                             #
+#                 ibm_db.execute()                                                             #
+#                 ibm_db.num_rows()                                                            #
+#                 ibm_db.free_result()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+preparedStmt = False
+resultSet = False
+returnCode = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Define The SQL Statement That Is To Be Executed
+sqlStatement = "SELECT * FROM employee WHERE edlevel > 17"
+
+# Prepare The SQL Statement Just Defined
+print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="")
+try:
+    preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit
+if preparedStmt is False:
+    print("\nERROR: Unable to prepare the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Execute The SQL Statement Just Prepared
+print("Executing the prepared SQL statement ... ", end="")
+try:
+    resultSet = ibm_db.execute(preparedStmt)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Just Executed
+# (This Information Should Not Be Available)
+try:
+    numRows = ibm_db.num_rows(preparedStmt)
+except Exception:
+    pass
+ 
+# Display An Appropriate Message, Based On The Information Returned
+if numRows <= 0:
+    print("Unable to obtain information about the number of rows returned.\n")
+else:
+    print("Number of rows returned by the query: " + str(numRows) + "\n")
+
+# Free System Resources That Are Associated With The Prepared Statement And Result Set Produced
+print("Freeing system resources associated with the prepared statement ... ", end="")
+try:
+    returnCode = ibm_db.free_result(preparedStmt)
+except Exception:
+    pass
+
+# If The Appropriate System Resources Could Not Be Freed, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to free the appropriate system resources.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Create A Dictionary That Contains The Value Needed To Turn Row Prefetch Behavior On;
+# This Enables Db2 To Determine The Number Of Rows That Are Returned By A Query (So The
+# Entire Result Set Can Be Prefetched Into Memory, When Possible) 
+stmtOption = {ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON}
+
+# Attempt To Set The Statement Option Specified
+print("Turning SQL_ATTR_ROWCOUNT_PREFETCH behavior ON ... ", end="")
+try:
+    returnCode = ibm_db.set_option(preparedStmt, stmtOption, 0)
+except Exception:
+    pass
+
+# If The Statement Option Could Not Be Set, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to set the statement option specified.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Execute The Prepared SQL Statement Again
+print("Executing the prepared SQL statement again ... ", end="")
+try:
+    resultSet = ibm_db.execute(preparedStmt)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement specified.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Again
+# (This Time, The Information Should Be Available)
+try:
+    numRows = ibm_db.num_rows(preparedStmt)
+except Exception:
+    pass
+
+# Display An Appropriate Message, Based On The New Information Returned
+if numRows <= 0:
+    print("Unable to obtain information about the number of rows returned.\n")
+else:
+    print("Number of rows returned by the query: " + str(numRows) + "\n")
+
+# Free The Appropriate System Resources Again
+try:
+    returnCode = ibm_db.free_result(preparedStmt)
+except Exception:
+    pass
+
+# If The Appropriate System Resources Could Not Be Freed, Display An Error Message And Exit 
+if returnCode is False:
+    print("\nERROR: Unable to free the appropriate system resources.\n")
+    conn.closeConnection()
+    exit(-1)
+        
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Preparing the SQL statement "SELECT * FROM employee WHERE edlevel > 17" ... Done!
+
+Executing the prepared SQL statement ... Done!
+
+Unable to obtain information about the number of rows returned.
+
+Freeing system resources associated with the prepared statement ... Done!
+
+Turning SQL_ATTR_ROWCOUNT_PREFETCH behavior ON ... Done!
+
+Executing the prepared SQL statement again ... Done!
+
+Number of rows returned by the query: 9
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-special_columns.html b/python_samples/HTML_Documentation/ibm_db-special_columns.html new file mode 100644 index 0000000..5aa507c --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-special_columns.html @@ -0,0 +1,13462 @@ + + + + +ibm_db-special_columns + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.special_columns()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve a list of unique row identifier columns and their associated metadata, for a table.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.special_columns( IBM_DBConnectionconnection,stringqualifierName,
stringschemaName,stringtableName,intscope)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection        : A valid Db2 server or database connection.
  • +
  • qualifierName    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value None or an empty string ('') for Db2 databases on other operating systems.
  • +
  • schemaName     : The name of the schema that contains the table(s) that unique row identifier column information is to be obtained for.
  • +
  • tableName          : The name of the table that unique identifier column information is to be obtained for.
  • +
  • scope                  : The minimum duration for which the unique row identifier column is guaranteed to point to the same row. Valid values for this parameter are:

    +
      +
    • 0   : The row identifier is guaranteed to be valid only while the cursor is positioned on the current row.
    • +
    • 1   : The row identifier is guaranteed to be valid for the duration of the transaction.
    • +
    • 2   : The row identifier is guaranteed to be valid for the duration of the connection.
    • +
    +
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an IBM_DBStatement with a result set that contains the following information:

    +
      +
    • SCOPE                      : A value that indicates the minimum duration for which the unique row identifier is guaranteed to point to the same row. Valid values for this field are:

      +
        +
      • 0   : The row identifier is guaranteed to be valid only while the cursor is positioned on the current row.
      • +
      • 1   : The row identifier is guaranteed to be valid for the duration of the transaction.
      • +
      • 2   : The row identifier is guaranteed to be valid for the duration of the connection.

      • +
      +
    • +
    • COLUMN_NAME         : The name of the column that is the primary key or part of the primary key of the table.

      +
    • +
    • DATA_TYPE              : An integer value that represents the SQL data type of the column. On Linux and UNIX systems, valid values for this field can be found in the file /opt/ibm/db2/V11.1/include/sqlcli.h.
    • +
    • TYPE_NAME              : The data source-specific string representation of the SQL data type of the column.
    • +
    • COLUMN_SIZE          : The maximum number of bytes needed to display the column's data as a string.
    • +
    • BUFFER_LENGTH      : The maximum number of bytes needed to store the column's data in an application variable.
    • +
    • DECIMAL_DIGITS    : The scale (i.e., total number of significant digits to the right of the decimal point) of the column - provided the column has a numerical data type. If the column does not have a numerical data type, this field will contain the value None.
    • +
    • NUM_PREC_RADIX    : A numerical value that indicates whether the column's data type represents an exact numeric data type (10) or an approximate numeric data type (2). If the column does not have a numerical data type, this field will contain the value None.
    • +
    • PSEUDO_COLUMN      : Indication of whether the column is a pseudo-column (a "column" that returns a value when selected, but is not an actual column of the table) or not. This field will always contain the value 1, which means the column is NOT a pseudo-column.

    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.special_columns() API is used to retrieve information about unique row identifier columns that have been created for a table. (Columns used to create a primary key or unique index are referred to as unique row identifier columns.)

+

The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-special_columns.py                                                         #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.special_columns()    #
+#            API.                                                                              #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.fetch_assoc()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+schemaName = userID.upper()
+tableName = "EMPLOYEE"
+resultSet = False
+dataRecord = False
+sqlDataTypes = {0 : "SQL_UNKNOWN_TYPE", 1 : "SQL_CHAR", 2 : "SQL_NUMERIC", 3 : "SQL_DECIMAL",
+    4 : "SQL_INTEGER", 5 : "SQL_SMALLINT", 6 : "SQL_FLOAT", 7 : "SQL_REAL", 8 : "SQL_DOUBLE",
+    9 : "SQL_DATETIME", 12 : "SQL_VARCHAR", 16 : "SQL_BOOLEAN", 19 : "SQL_ROW", 
+    91 : "SQL_TYPE_DATE", 92 : "SQL_TYPE_TIME", 93 : "SQL_TYPE_TIMESTAMP",
+    95 : "SQL_TYPE_TIMESTAMP_WITH_TIMEZONE", -8 : "SQL_WCHAR", -9 : "SQL_WVARCHAR",
+    -10 : "SQL_WLONGVARCHAR", -95 : "SQL_GRAPHIC", -96 : "SQL_VARGRAPHIC",
+    -97 : "SQL_LONGVARGRAPHIC", -98 : "SQL_BLOB", -99 : "SQL_CLOB", -350 : "SQL_DBCLOB",
+    -360 : "SQL_DECFLOAT", -370 : "SQL_XML", -380 : "SQL_CURSORHANDLE", -400 : "SQL_DATALINK",
+    -450 : "SQL_USER_DEFINED_TYPE"}
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Retrieve Information About Unique Row Identifier Columns That Have Been 
+# Defined For The Table Specified
+print("Obtaining information about unique row identifier columns that have been")
+print("defined for the " + schemaName + "." + tableName + " table ... ", end="")
+try:
+    resultSet = ibm_db.special_columns(dbConnection, None, schemaName, tableName, 0)
+
+except Exception:
+    pass
+
+# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit
+if resultSet is False:
+    print("\nERROR: Unable to obtain the information desired\n.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# As Long As There Are Records (That Were Produced By The ibm_db.special_columns API), ...
+noData = False
+loopCounter = 1
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop  
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Information Retrieved
+    else:
+
+        # Display Record Header Information
+        print("Primary key/unique index " + str(loopCounter) + " details:")
+        print("___________________________________")
+
+        # Display The Information Stored In The Data Record Retrieved
+        print("Column name            : {}" .format(dataRecord['COLUMN_NAME']))
+        print("Data type              : {}" .format(dataRecord['TYPE_NAME']))
+        print("SQL data type          : ", end="")
+        print(sqlDataTypes.get(dataRecord['DATA_TYPE']))
+        print("Column size            : {}" .format(dataRecord['COLUMN_SIZE']))
+        print("Buffer size            : {}" .format(dataRecord['BUFFER_LENGTH']))
+        print("Scale (decimal digits) : {}" .format(dataRecord['DECIMAL_DIGITS']))
+
+        print("Scope                  : ", end="")
+        if dataRecord['SCOPE'] == 0:
+            print("Row ID is valid only while the\n" + " " * 25, end="")
+            print("cursor is positioned on the row")
+        elif dataRecord['SCOPE'] == 1:
+            print("Row ID is valid for the\n" + " " * 25, end="")
+            print("duration of the transaction")
+        elif dataRecord['SCOPE'] == 2:
+            print("Row ID is valid for the\n" + " " * 25, end="")
+            print("duration of the connection")
+
+        # Increment The loopCounter Variable And Print A Blank Line To Separate The
+        # Records From Each Other
+        loopCounter += 1
+        print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Obtaining information about unique row identifier columns that have been
+defined for the DB2INST1.EMPLOYEE table ... Done!
+
+Primary key/unique index 1 details:
+___________________________________
+Column name            : EMPNO
+Data type              : CHAR
+SQL data type          : SQL_CHAR
+Column size            : 6
+Buffer size            : 6
+Scale (decimal digits) : None
+Scope                  : Row ID is valid only while the
+                         cursor is positioned on the row
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-statistics.html b/python_samples/HTML_Documentation/ibm_db-statistics.html new file mode 100644 index 0000000..920fa09 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-statistics.html @@ -0,0 +1,13513 @@ + + + + +ibm_db-statistics + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.statistics()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve statistical information for a table and its associated indexes.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.statistics( IBM_DBConnectionconnection,stringqualifierName,
stringschemaName,stringtableName,booluniqueIndicator)

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection            : A valid Db2 server or database connection.
  • +
  • qualifierName        : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value None or an empty string ('') for Db2 databases on other operating systems.
  • +
  • schemaName         : The name of the schema that contains the table that statistical information is to be obtained for. To isolate the search for information to the schema for the current user, provide the value None or an empty string.
  • +
  • tableName              : The name of the table that statistical information is to be obtained for.
  • +
  • uniqueIndicator     : A value that indicates whether statistical information should be retreived for all indexes that have been defined for the table specified—or just for unique indexes. Valid values for this parameter are:

    +
      +
    • True     : Only retrieve information for unique indexes.
    • +
    • False   : Retrieve information for all indexes.
    • +
    +
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an IBM_DBStatement with a result set that contains the following information:

    +
      +
    • TYPE                          : A value that identifies the type of information contained in the current row (record) in this result set. Valid values for this field are:

      +
        +
      • ibm_db.SQL_TABLE_STAT             : The current row contains statistical information about the table itself.
      • +
      • ibm_db.SQL_INDEX_CLUSTERED   : The current row contains statistical information for a clustered index.
      • +
      • ibm_db.SQL_INDEX_OTHER           : The current row contains statistical information for some other type of index.

      • +
      +
    • +
    • TABLE_CAT                : The name of the catalog associated with the schema and table the statistical information is for; Db2 does not use catalogs so this field will always contain the value None. (Db2 databases on OS/390 or z/OS servers can return information in this field.)

      +
    • +
    • TABLE_SCHEM            : The name of the schema for the table the statistical information is associated with.
    • +
    • TABLE_NAME              : The name of the table to which the statistical information applies.
    • +
    • INDEX_NAME              : The name of the index to which the statistical information applies.
    • +
    • INDEX_QUALIFIER    : The character string that would have to be prepended to the index name (INDEX_NAME) to fully qualify the name in a DROP INDEX statement.
    • +
    • NON_UNIQUE              : A value that indicates whether the index allows or prohibits duplicate values. Valid values for this field are:

      +
        +
      • ibm_db.SQL_TRUE     : The index allows duplicate values.
      • +
      • ibm_db.SQL_FALSE   : The index values must be unique.
      • +
      • None                           : The TYPE field indicates the current row contains statistical information about the table - not an index.

      • +
      +
    • +
    • ORDINAL_POSITION  : The column's ordinal position in the index, starting from 1. If the TYPE field indicates the current row contains statistical information about the table, this field will contain the value None.

      +
    • +
    • COLUMN_NAME             : The name of the column in the index. If the TYPE field indicates the current row contains statistical information about the table, this field will contain the value None.
    • +
    • ASC_OR_DESC             : A value that identifies the sort sequence that is used to order the column's data. Valid values for this field are:

      +
        +
      • 'A'     : The column's data is sorted in ascending order.
      • +
      • 'D'     : The column's data is sorted in descending order.
      • +
      • None   : The TYPE field indicates the current row contains statistical information about the table - not an index.

      • +
      +
    • +
    • CARDINALITY            : If the TYPE field indicates the current row contains statistical information about the table, this field will contain the number of rows found in the table. If the current row contains statistical information about an index, this field will contain the number of unique values found in the index.

      +
    • +
    • PAGES                        : The number of pages used to store the table or index.
    • +
    • FILTER_CONDITION  : Identifies the filter condition used if the index is a filtered index; Db2 does not support filtered indexes so this field will always contain the value None.

    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.statistics() API is used to retrieve statistical information for a table and its associated indexes. When invoked, this API can return two types of information:

+
    +
  • Statistical information about the table itself (if that information is available).
  • +
  • Statistical information about any indexes that have been defined for the table.

  • +
+

The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-statistics.py                                                              #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.statistics() API.    #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.fetch_assoc()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+schemaName = userID.upper()
+tableName = "EMPLOYEE"
+resultSet = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Retrieve Information About The Indexes And Statistics That Exist For A 
+# Specified Table
+print("Obtaining statistics for the " + schemaName + ".", end="")
+print(tableName + " table ... ", end="")
+try:
+    resultSet = ibm_db.statistics(dbConnection, None, schemaName, tableName, True)
+except Exception:
+    pass
+
+# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit
+if resultSet is False:
+    print("\nERROR: Unable to obtain the information desired\n.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# As Long As There Are Records (That Were Produced By The ibm_db.statistics API), ...
+noData = False
+loopCounter = 1
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop  
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Information Retrieved
+    else:
+
+        # Display Record Header Information
+        print("Record number " + str(loopCounter) + " details:")
+        print("______________________________________________")
+
+        # Display The Information Stored In The Data Record Retrieved
+        print("Type of data                     : ", end="")
+        if dataRecord['TYPE'] == ibm_db.SQL_TABLE_STAT:
+            print("Table")
+        elif dataRecord['TYPE'] == ibm_db.SQL_INDEX_CLUSTERED:
+            print("Clustered index")
+        elif dataRecord['TYPE'] == ibm_db.SQL_INDEX_OTHER:
+            print("Index")
+        print("Table schema                     : {}" .format(dataRecord['TABLE_SCHEM']))
+        print("Table name                       : {}" .format(dataRecord['TABLE_NAME']))
+        print("Index qualifier                  : {}" .format(dataRecord['INDEX_QUALIFIER']))
+        print("Index name                       : {}" .format(dataRecord['INDEX_NAME']))
+        print("Column name                      : {}" .format(dataRecord['COLUMN_NAME']))
+        print("Column position in index         : {}" .format(dataRecord['ORDINAL_POSITION']))
+        if not dataRecord['INDEX_NAME'] is None:
+            print("Index used to enforce uniqueness : ", end="")
+            if dataRecord['NON_UNIQUE'] == ibm_db.SQL_FALSE:
+                print("No")
+            elif dataRecord['NON_UNIQUE'] == ibm_db.SQL_TRUE:
+                print("Yes")
+        if not dataRecord['INDEX_NAME'] is None:
+            print("Data order                       : ", end="")
+            if dataRecord['ASC_OR_DESC'] == 'A':
+                print("Ascending")
+            elif dataRecord['ASC_OR_DESC'] == 'D':
+                print("Descending")
+        if not dataRecord['INDEX_NAME'] is None:
+            print("Number of unique values          : {}" .format(dataRecord['CARDINALITY']))
+        else:
+            print("Number of rows (records)         : {}" .format(dataRecord['CARDINALITY']))
+
+        print("Number of pages used             : {}" .format(dataRecord['PAGES']))
+
+        # Increment The loopCounter Variable And Print A Blank Line To Separate The
+        # Records From Each Other
+        loopCounter += 1
+        print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Obtaining statistics for the DB2INST1.EMPLOYEE table ... Done!
+
+Record number 1 details:
+______________________________________________
+Type of data                     : Index
+Table schema                     : DB2INST1
+Table name                       : EMPLOYEE
+Index qualifier                  : DB2INST1
+Index name                       : PK_EMPLOYEE
+Column name                      : EMPNO
+Column position in index         : 1
+Index used to enforce uniqueness : No
+Data order                       : Ascending
+Number of unique values          : 42
+Number of pages used             : 1
+
+Record number 2 details:
+______________________________________________
+Type of data                     : Index
+Table schema                     : DB2INST1
+Table name                       : EMPLOYEE
+Index qualifier                  : DB2INST1
+Index name                       : XEMP2
+Column name                      : WORKDEPT
+Column position in index         : 1
+Index used to enforce uniqueness : Yes
+Data order                       : Ascending
+Number of unique values          : 8
+Number of pages used             : 1
+
+Record number 3 details:
+______________________________________________
+Type of data                     : Table
+Table schema                     : DB2INST1
+Table name                       : EMPLOYEE
+Index qualifier                  : None
+Index name                       : None
+Column name                      : None
+Column position in index         : None
+Number of rows (records)         : 42
+Number of pages used             : 1
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-stmt_error.html b/python_samples/HTML_Documentation/ibm_db-stmt_error.html new file mode 100644 index 0000000..067525e --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-stmt_error.html @@ -0,0 +1,13388 @@ + + + + +ibm_db-stmt_error + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.stmt_error()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Return an SQLSTATE value associated with an IBM_DBStatement object.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

string ibm_db.stmt_error( [ IBM_DBStatementstatement] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object.
  • +
+ +
+
+
+
+
+
+

Return Values:

+
+
+
+
+
+
+

When a statement value is provided:

+
    +
  • If there is an error associated with the IBM_DBStatement object specified, a string containing an SQLSTATE value that explains why the last operation using the IBM_DBStatement object failed.
  • +
  • If there is no error associated with the IBM_DBStatement object specified, an empty string ('').
  • +
+ +
+
+
+
+
+
+

When a statement value is not provided:

+
    +
  • If there is an error associated with the last attempt to return an IBM_DBStatement object from an ibm_db.prepare(), ibm_db.exec_immediate(), or ibm_db.callproc() API, a string containing an SQLSTATE value that explains why the API failed.
  • +
  • If there is no error associated with the last attempt to return an IBM_DBStatement object, an empty string ('').
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.stmt_error() API can be used to return an SQLSTATE value that explains why an attempt to return an IBM_DBStatement object from an ibm_db.prepare(), ibm_db.exec_immediate(), or ibm_db.callproc() API call was not successful. It can also be used to return an SQLSTATE value that identifies why the last operation using a IBM_DBStatement object failed.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-stmt_error.py                                                              #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.stmt_error() API.    #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.exec_immediate()                                                      #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+sqlStatement = " "           # An Empty SQL Statement Is Used To Force An Error To Occur
+resultSet = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Execute The SQL Statement Specified
+print("Executing the SQL statement specified ... ", end="")
+try:
+    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit 
+if resultSet is False:
+    print("\nERROR: Unable to execute the SQL statement.")
+    errorCode = ibm_db.stmt_error()
+    print("\nSQLSTATE: "+ errorCode + "\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Executing the SQL statement specified ... 
+ERROR: Unable to execute the SQL statement.
+
+SQLSTATE: 42617
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+ +
+ + +
+
+An exception has occurred, use %tb to see the full traceback.
+
+ipynb_Exit
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-stmt_errormsg.html b/python_samples/HTML_Documentation/ibm_db-stmt_errormsg.html new file mode 100644 index 0000000..09c69e3 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-stmt_errormsg.html @@ -0,0 +1,13389 @@ + + + + +ibm_db-stmt_errormsg + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.stmt_errormsg()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Return an SQLCODE and corresponding error message associated with an IBM_DBStatement object.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

string ibm_db.stmt_errormsg( [ IBM_DBStatementstatement] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • statement    : A valid IBM_DBStatement object.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+

When a statement value is provided:

+
    +
  • If there is an error associated with the IBM_DBStatement object specified, a string containing an SQLCODE and corresponding error message that explains why the last operation using the IBM_DBStatement object failed.
  • +
  • If there is no error associated with the IBM_DBStatement object specified, an empty string ('').
  • +
+ +
+
+
+
+
+
+

When a statement value is not provided:

+
    +
  • If there is an error associated with the last attempt to return an IBM_DBStatement object from an ibm_db.prepare(), ibm_db.exec_immediate(), or ibm_db.callproc() API, a string containing an SQLCODE and corresponding error message that explains why the API failed.
  • +
  • If there is no error associated with the last attempt to return an IBM_DBStatement object, an empty string ('').
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.stmt_errormsg() API can be used to return an SQLCODE and corresponding error message that explains why an attempt to return an IBM_DBStatement object from an ibm_db.prepare(), ibm_db.exec_immediate(), or ibm_db.callproc() API call was not successful. It can also be used to return an SQLCODE and error message that identifies why the last operation using a IBM_DBStatement object failed.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-stmt_errormsg.py                                                           #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.stmt_errormsg() API. #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.prepare()                                                             #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+sqlStatement = " "           # An Empty SQL Statement Is Used To Force An Error To Occur
+preparedStmt = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Prepare The SQL Statement Specified
+print("Preparing the SQL statement specified for execution ... ", end="")
+try:
+    preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)
+except Exception:
+    pass
+
+# If Db2 Could Not Parse And Prepare The SQL Statement Correctly, Display An Error Message
+# And Exit
+if preparedStmt is False:
+    print("\nERROR: Unable to prepare the SQL statement specified.")
+    errorMsg = ibm_db.stmt_errormsg()
+    print("\n" + errorMsg + "\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Preparing the SQL statement specified for execution ... 
+ERROR: Unable to prepare the SQL statement specified.
+
+[IBM][CLI Driver][DB2/LINUXX8664] SQL0198N  The statement string of the PREPARE or EXECUTE IMMEDIATE statement is blank or empty.  SQLSTATE=42617 SQLCODE=-198
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+ +
+ + +
+
+An exception has occurred, use %tb to see the full traceback.
+
+ipynb_Exit
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-table_privileges.html b/python_samples/HTML_Documentation/ibm_db-table_privileges.html new file mode 100644 index 0000000..1f26840 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-table_privileges.html @@ -0,0 +1,13484 @@ + + + + +ibm_db-table_privileges + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.table_privileges()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve a list of tables and their associated privileges.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.table_privileges( IBM_DBConnectionconnection[, stringqualifierName
[, stringschemaName[, stringtableName] ] ] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection        : A valid Db2 server or database connection.
  • +
  • qualifierName    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value None or an empty string ('') for Db2 databases on other operating systems.
  • +
  • schemaName     : The name of the schema that contains the table(s) that information is to be obtained for. To match all schemas, provide the value None or an empty string; to match select schemas, provide a search pattern that contains _ and/or % wildcards.
  • +
  • tableName          : The name of the table(s) that information is to be obtained for. To match all tables, provide the value None or an empty string; to match select tables, provide a search pattern that contains _ and/or % wildcards.
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an IBM_DBStatement with a result set that contains the following information:

    +
      +
    • TABLE_CAT        : The name of the catalog associated with the schema and table the table privilege is for; Db2 does not use catalogs so this field will always contain the value None. (Db2 databases on OS/390 or z/OS servers can return information in this field.)
    • +
    • TABLE_SCHEM    : The name of the schema for the table the privilege is associated with.
    • +
    • TABLE_NAME      : The name of the table the privilege is associated with.
    • +
    • PRIVILEGE        : The table privilege. Valid values are ALTER, CONTROL, DELETE, INDEX, INSERT, REFERENCES, SELECT, and UPDATE.
    • +
    • GRANTOR            : The authorization ID of the user who granted the privilege.
    • +
    • GRANTEE            : The authorization ID of the user to whom the privilege was granted.
    • +
    • IS_GRANTABLE  : Indication of whether the authorization ID of the user to whom the privilege was granted (the GRANTEE) is permitted to grant the privilege to others. Valid values are YES and NO.

    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.table_privileges() API is used to retrieve a list of tables and the privileges associated with them.

+

The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-table_privileges.py                                                        #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.table_privileges()   #
+#            API.                                                                              #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.fetch_assoc()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+schemaName = userID.upper()
+tableName = "PROJECT"
+resultSet = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Retrieve Information About All Of The Privileges That Have Been Defined For The
+# Table Specified
+print("Obtaining information about privileges that exist for the ", end="")
+print(schemaName + "." + tableName + " table ... ", end="")
+try:
+    resultSet = ibm_db.table_privileges(dbConnection, None, schemaName, tableName)
+except Exception:
+    pass
+
+# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit
+if resultSet is False:
+    print("\nERROR: Unable to obtain the information desired.\n")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# As Long As There Are Records (That Were Produced By The ibm_db.table_privileges API), ...
+noData = False
+loopCounter = 1
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop 
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Information Retrieved
+    else:
+
+        # Display Record Header Information
+        print("Table privilege " + str(loopCounter) + " details:")
+        print("___________________________________")
+
+        # Display The Information Stored In The Data Record Retrieved
+        print("Schema name            : {}" .format(dataRecord['TABLE_SCHEM']))
+        print("Table name             : {}" .format(dataRecord['TABLE_NAME']))
+        print("Privilege grantor      : {}" .format(dataRecord['GRANTOR']))
+        print("Privilege recipient    : {}" .format(dataRecord['GRANTEE']))
+        print("Privilege              : {}" .format(dataRecord['PRIVILEGE']))
+        print("Privilege is grantable : {}" .format(dataRecord['IS_GRANTABLE']))
+
+        # Increment The loopCounter Variable And Print A Blank Line To Separate The
+        # Records From Each Other
+        loopCounter += 1
+        print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Obtaining information about privileges that exist for the DB2INST1.PROJECT table ... Done!
+
+Table privilege 1 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : ALTER
+Privilege is grantable : YES
+
+Table privilege 2 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : CONTROL
+Privilege is grantable : NO
+
+Table privilege 3 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : DELETE
+Privilege is grantable : YES
+
+Table privilege 4 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : INDEX
+Privilege is grantable : YES
+
+Table privilege 5 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : INSERT
+Privilege is grantable : YES
+
+Table privilege 6 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : REFERENCES
+Privilege is grantable : YES
+
+Table privilege 7 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : SELECT
+Privilege is grantable : YES
+
+Table privilege 8 details:
+___________________________________
+Schema name            : DB2INST1
+Table name             : PROJECT
+Privilege grantor      : SYSIBM
+Privilege recipient    : DB2INST1
+Privilege              : UPDATE
+Privilege is grantable : YES
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/ibm_db-tables.html b/python_samples/HTML_Documentation/ibm_db-tables.html new file mode 100644 index 0000000..d32cc64 --- /dev/null +++ b/python_samples/HTML_Documentation/ibm_db-tables.html @@ -0,0 +1,13434 @@ + + + + +ibm_db-tables + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+

ibm_db.tables()

+
+
+
+
+
+
+

Purpose:

+
+
+
+
+
+
+

Retrieve a list of tables and their associated metadata.

+ +
+
+
+
+
+
+

Syntax:

+
+
+
+
+
+
+

IBM_DBStatement ibm_db.tables( IBM_DBConnectionconnection[, stringqualifierName[, stringschemaName[, stringtableName[, stringtableType] ] ] ] )

+ +
+
+
+
+
+
+

Parameters:

+
+
+
+
+
+
+
    +
  • connection        : A valid Db2 server or database connection.
  • +
  • qualifierName    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value None or an empty string ('') for Db2 databases on other operating systems.
  • +
  • schemaName     : The name of the schema that contains the table(s) that information is to be obtained for. To match all schemas, provide the value None or an empty string; to match select schemas, provide a search pattern that contains _ and/or % wildcards.
  • +
  • tableName          : The name of the table(s) that information is to be obtained for. To match all tables, provide the value None or an empty string; to match select tables, provide a search pattern that contains _ and/or % wildcards.
  • +
  • tableType           : The type(s) of table(s) that information is to be obtained for. To match all table types, provide the value None or an empty string; to match specific table type(s), provide one or more of the following values (use a comma delimiter to separate values):

    +
      +
    • 'ALIAS'                                           : Obtain information for aliases.
    • +
    • 'TABLE'                                           : Obtain information for tables.
    • +
    • 'TYPED TABLE'                               : Obtain information for typed tables.
    • +
    • 'SYSTEM TABLE'                             : Obtain information for system catalog tables.
    • +
    • 'HIERARCHY TABLE'                       : Obtain information for hierarchy tables.
    • +
    • 'MATERIALIZED QUERY TABLE'     : Obtain information for materialized query tables (MQTs) tables.
    • +
    • 'VIEW'                                             : Obtain information for views.
    • +
    • 'TYPED VIEW'                                 : Obtain information for typed views.
    • +
    • 'INOPERATIVE VIEW'                     : Obtain information for inoperative views.
    • +
    • 'NICKNAME'                                     : Obtain information for nicknames.
    • +
    +
  • +
+ +
+
+
+
+
+
+

Return values:

+
+
+
+
+
+
+
    +
  • If successful, an IBM_DBStatement with a result set that contains the following information:

    +
      +
    • TABLE_CAT        : The name of the catalog associated with the schema and table; Db2 does not use catalogs so this field will always contain the value None. (Db2 databases on OS/390 or z/OS servers can return information in this field.)
    • +
    • TABLE_SCHEM    : The name of the schema that contains the table.
    • +
    • TABLE_NAME      : The name of the table.
    • +
    • TABLE_TYPE      : The type identifier for the table. (Refer to the tableType parameter for a list of the table type identifiers available.)
    • +
    • REMARKS            : A user-supplied description of the table (if one has been provided).

    • +
    +
  • +
  • If unsuccessful, the value False.

    +
  • +
+ +
+
+
+
+
+
+

Description:

+
+
+
+
+
+
+

The ibm_db.tables() API is used to retrieve a list of tables and all associated metadata, for one or more table types.

+

The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the ibm_db.fetch_tuple() (tuple), ibm_db.fetch_assoc() (dictionary), or ibm_db.fetch_both() (tuple and dictionary) APIs. Alternately, the ibm_db.fetch_row() API can be used to move the result set pointer to each row in the result set produced and the ibm_db.result() API can be used to fetch a column from the current row.

+ +
+
+
+
+
+
+

Example:

+
+
+
+
+
+
In [1]:
+
+
+
#----------------------------------------------------------------------------------------------#
+#  NAME:     ibm_db-tables.py                                                                  #
+#                                                                                              #
+#  PURPOSE:  This program is designed to illustrate how to use the ibm_db.tables() API.        #
+#                                                                                              #
+#            Additional APIs used:                                                             #
+#                 ibm_db.fetch_assoc()                                                         #
+#                                                                                              #
+#----------------------------------------------------------------------------------------------#
+#                     DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY                     #
+#                                                                                              #
+#  (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved          #
+#  Licensed Materials - Property of IBM                                                        #
+#                                                                                              #
+#  US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA    #
+#  ADP Schedule Contract with IBM Corp.                                                        #
+#                                                                                              #
+#  The following source code ("Sample") is owned by International Business Machines            #
+#  Corporation ("IBM") or one of its subsidiaries and is copyrighted and licensed, not sold.   #
+#  You may use, copy, modify, and distribute the Sample in any form without payment to IBM,    #
+#  for the purpose of assisting you in the creation of Python applications using the ibm_db    #
+#  library.                                                                                    #
+#                                                                                              #
+#  The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM   #
+#  HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT    #
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #
+#  Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so   #
+#  the above limitations or exclusions may not apply to you. IBM shall not be liable for any   #
+#  damages you suffer as a result of using, copying, modifying or distributing the Sample,     #
+#  even if IBM has been advised of the possibility of such damages.                            #
+#----------------------------------------------------------------------------------------------#
+
+# Load The Appropriate Python Modules
+import sys         # Provides Information About Python Interpreter Constants And Functions
+import ibm_db      # Contains The APIs Needed To Work With Db2 Databases
+
+#----------------------------------------------------------------------------------------------#
+# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #
+# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To     #
+# Establish And Terminate A Connection To A Db2 Server Or Database                             #
+#----------------------------------------------------------------------------------------------#
+from ibm_db_tools import Db2ConnectionMgr
+
+#----------------------------------------------------------------------------------------------#
+# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In    #
+# The File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow    #
+# "exit()" Functionality To Work Without Raising An Error Or Stopping The Kernel If The        #
+# Application Is Invoked In A Jupyter Notebook                                                 #
+#----------------------------------------------------------------------------------------------#
+from ipynb_exit import exit
+
+# Define And Initialize The Appropriate Variables
+dbName = "SAMPLE"
+userID = "db2inst1"
+passWord = "Passw0rd"
+dbConnection = None
+schemaName = userID.upper()
+resultSet = False
+dataRecord = False
+
+# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
+conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
+conn.openConnection()
+if conn.returnCode is True:
+    dbConnection = conn.connectionID
+else:
+    conn.closeConnection()
+    exit(-1)
+
+# Attempt To Retrieve Information About The Tables In The Current User's Schema Whose Name
+# Begins With The Letter "P"
+print("Obtaining information about select tables in the ", end="")
+print(schemaName + " schema ... ", end="")
+try:
+    resultSet = ibm_db.tables(dbConnection, None, schemaName, 'P%', 'TABLE')
+except Exception:
+    pass
+
+# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit
+if resultSet is False:
+    print("\nERROR: Unable to obtain the information desired\n.")
+    conn.closeConnection()
+    exit(-1)
+
+# Otherwise, Complete The Status Message
+else:
+    print("Done!\n")
+
+# As Long As There Are Records (That Were Produced By The ibm_db.tables API), ...
+noData = False
+loopCounter = 1
+while noData is False:
+
+    # Retrieve A Record And Store It In A Python Dictionary
+    try:
+        dataRecord = ibm_db.fetch_assoc(resultSet)
+    except:
+        pass
+
+    # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The
+    # "No Data" Flag And Exit The Loop  
+    if dataRecord is False:
+        noData = True
+
+    # Otherwise, Display The Information Retrieved
+    else:
+
+        # Display Record Header Information
+        print("Table " + str(loopCounter) + " details:")
+        print("________________________")
+
+        # Display The Information Stored In The Data Record Retrieved
+        print("Table schema  : {}" .format(dataRecord['TABLE_SCHEM']))
+        print("Table name    : {}" .format(dataRecord['TABLE_NAME']))
+        print("Table type    : {}" .format(dataRecord['TABLE_TYPE']))
+        print("Description   : {}" .format(dataRecord['REMARKS']))
+
+        # Increment The loopCounter Variable And Print A Blank Line To Separate The
+        # Records From Each Other
+        loopCounter += 1
+        print()
+
+# Close The Database Connection That Was Opened Earlier
+conn.closeConnection()
+
+# Return Control To The Operating System
+exit()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
+Connecting to the SAMPLE database ... Done!
+
+Obtaining information about select tables in the DB2INST1 schema ... Done!
+
+Table 1 details:
+________________________
+Table schema  : DB2INST1
+Table name    : PROJACT
+Table type    : TABLE
+Description   : None
+
+Table 2 details:
+________________________
+Table schema  : DB2INST1
+Table name    : PROJECT
+Table type    : TABLE
+Description   : None
+
+Disconnecting from the SAMPLE database ... Done!
+
+
+
+
+ +
+
+ +
+
+
+
In [ ]:
+
+
+
 
+
+ +
+
+
+ +
+
+
+ + + + + + diff --git a/python_samples/HTML_Documentation/readme.md b/python_samples/HTML_Documentation/readme.md new file mode 100644 index 0000000..0f4378d --- /dev/null +++ b/python_samples/HTML_Documentation/readme.md @@ -0,0 +1 @@ +This directory contains HTML files that document how to use the APIs found in the ibm_db library. diff --git a/python_samples/Jupyter_Notebooks/ibm_db-active.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-active.ipynb new file mode 100644 index 0000000..fb7bb33 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-active.ipynb @@ -0,0 +1,258 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.active()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Determine whether the Db2 server or database connection specified is active." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.active( IBM_DBConnection `*`connection`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server or database connection." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : The Db2 server or database connection specified is active. \n", + "* `False`    : The Db2 server or database connection specified is not active." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.active()__ API is used to determine if a Db2 server or database connection that was established using the __ibm_db.connect()__ API or __ibm_db.pconnect()__ is active.

" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "The connection to the SAMPLE database is ACTIVE.\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-active.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.active() API. #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Determine Whether The Current Database Connection Is Active Or Inactive\n", + "try:\n", + " connState = ibm_db.active(dbConnection)\n", + "except Exception:\n", + " pass\n", + "\n", + "# Display A Status Message That Shows The Current Connection State\n", + "print(\"The connection to the \" + dbName + \" database is \", end=\"\")\n", + "if connState is True:\n", + " print(\"ACTIVE.\\n\")\n", + "elif connState is False:\n", + " print(\"NOT ACTIVE.\\n\")\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-autocommit.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-autocommit.ipynb new file mode 100644 index 0000000..992b79d --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-autocommit.ipynb @@ -0,0 +1,342 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.autocommit()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Determine or set the __AUTOCOMMIT__ behavior of a Db2 server or database connection." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`mixed ibm_db.autocommit( IBM_DBConnection `*`connection`*` [, bool `*`setting`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server or database connection.\n", + "* __*setting*__            : A constant that specifies whether auto-commit behavior is to be used. Valid values are:

\n", + "\n", + " * `ibm_db.SQL_AUTOCOMMIT_OFF`  : Do not use auto-commit behavior; require applications to end transactions by calling either the __ibm_db.commit()__ or the __ibm_db.rollback()__ API.\n", + " * `ibm_db.SQL_AUTOCOMMIT_ON`    : Use auto-commit behavior." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*setting*__ value is provided: \n", + "* `True`      : __AUTOCOMMIT__ behavior was successfully set to the __*setting*__ specified. \n", + "* `False`    : __AUTOCOMMIT__ behavior was not set to the __*setting*__ specified." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*setting*__ value is not provided: \n", + "* `0`      : __AUTOCOMMIT__ behavior is __OFF__. \n", + "* `1`      : __AUTOCOMMIT__ behavior is __ON__." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.autocommit()__ API can be used to determine if a Db2 server or database connection (that was established by calling the __ibm_db.connect()__ or __ibm_db.pconnect()__ API) is configured for __AUTOCOMMIT__ behavior. It can also be used to turn __AUTOCOMMIT__ behavior for a Db2 server or database connection __OFF__ or __ON__.

__AUTOCOMMIT__ behavior controls when transactions performing SQL operations against a database are made permanent (committed) or are backed out (rolled back). If __AUTOCOMMIT__ behavior is turned __ON__, transactions are committed automatically, immediately after they are executed. (In other words, each SQL operation is treated as a single transaction and when the operation completes, changes made to the database are made permanent.) If __AUTOCOMMIT__ behavior is turned __OFF__, transactions must be manually terminated by executing either the __ibm_db.commit()__ or the __ibm_db.rollback()__ API." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the 'SAMPLE' database ... Done!\n", + "\n", + "AUTOCOMMIT behavior is ON; turning it OFF ... Done!\n", + "\n", + "AUTOCOMMIT behavior is now OFF.\n", + "\n", + "Disconnecting from the 'SAMPLE' database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-autocommit.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.autocommit() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.connect() #\n", + "# ibm_db.close() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "connOption = {ibm_db.SQL_ATTR_AUTOCOMMIT: ibm_db.SQL_AUTOCOMMIT_ON}\n", + "dbConnection = None\n", + "\n", + "# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database\n", + "# Is About To Be Made\n", + "print(\"\\nConnecting to the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + "\n", + "# Construct The String That Will Be Used To Establish A Db2 Database Connection\n", + "connString = \"ATTACH=FALSE\" # Attach To A Database; Not A Server\n", + "connString += \";DATABASE=\" + dbName # Required To Connect To A Database \n", + "connString += \";PROTOCOL=TCPIP\"\n", + "connString += \";UID=\" + userID\n", + "connString += \";PWD=\" + passWord\n", + "\n", + "# Attempt To Establish A Connection To The Database Specified\n", + "try:\n", + " dbConnection = ibm_db.connect(connString, '', '', connOption)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit\n", + "if dbConnection is None:\n", + " print(\"\\nERROR: Unable to connect to the \\'\" + dbName + \"\\' database.\")\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Determine Whether Autocommit Behavior Is OFF or ON (Should Match The connOption Setting)\n", + "try:\n", + " returnCode = ibm_db.autocommit(dbConnection)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If Autocommit Behavior Is OFF, Turn It ON\n", + "if returnCode is 0:\n", + " print(\"AUTOCOMMIT behavior is OFF; turning it ON ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_ON)\n", + " except Exception:\n", + " pass\n", + " \n", + " # If AUTOCOMMIT Behavior Could Not Be Turned ON, Display An Error Message And Continue\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to turn AUTOCOMMIT behavior ON.\")\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# If Autocommit Behavior Is ON, Turn It OFF\n", + "elif returnCode is 1:\n", + " print(\"AUTOCOMMIT behavior is ON; turning it OFF ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_OFF)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If AUTOCOMMIT Behavior Could Not Be Turned OFF, Display An Error Message And Continue\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to turn AUTOCOMMIT behavior OFF.\")\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Check Autocommit Behavior Again And Display Its Status\n", + "try:\n", + " returnCode = ibm_db.autocommit(dbConnection)\n", + "except Exception:\n", + " pass\n", + "\n", + "if returnCode is 0:\n", + " print(\"AUTOCOMMIT behavior is now OFF.\\n\")\n", + "elif returnCode is 1:\n", + " print(\"AUTOCOMMIT behavior is now ON.\\n\")\n", + "\n", + "# Attempt To Close The Db2 Database Connection That Was Opened Earlier\n", + "if not dbConnection is None:\n", + " print(\"Disconnecting from the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.close(dbConnection)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + dbName + \" database.\")\n", + " exit(-1)\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-bind_param.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-bind_param.ipynb new file mode 100644 index 0000000..2c08175 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-bind_param.ipynb @@ -0,0 +1,407 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.bind_param()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Associate (bind) parameter markers coded in a prepared SQL statement with application variables. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.bind_param( IBM_DBStatement `*`preparedStmt,`*`int `*`paramNumber,`*` string `*`variable`*
`[, int `*`paramType`*` [, int `*`dataType`*` [, int `*`precision`*` [, int `*`scale`*` [, int `*`size`*`] ] ] ] ] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false + }, + "source": [ + "* __*preparedStmt*__     : A prepared SQL statement (returned by the __ibm_db.prepare()__ API).\n", + "* __*paramNumber*__    : The parameter marker's location in the SQL statement text. Parameter markers are numbered sequentially, from left to right as they appear in the statement, starting with 1.\n", + "* __*variable*__              : The variable to be bound to the parameter marker specified in the __*paramNumber*__ parameter.\n", + "* __*paramType*__         : The type of parameter marker being bound. Valid values are:

\n", + " \n", + " * `ibm_db.SQL_PARAM_INPUT`                 : The parameter marker is associated with an SQL statement other than a __CALL__ statement *or* the parameter marker is associated with an input parameter of a stored procedure being called.\n", + " * `ibm_db.SQL_PARAM_OUTPUT`               : The parameter marker is associated with an output parameter *or* the return value of a stored procedure being called.\n", + " * `ibm_db.SQL_PARAM_INPUT_OUTPUT`   : The parameter marker is associated with an input/output parameter of a stored procedure being called.\n", + " * `ibm_db.PARAM_FILE`                           : The parameter marker is associated with a file that contains the data that will be provided when the SQL statement is executed. (A file can be used to avoid having to store large object data in memory.)

\n", + " \n", + "* __*dataType*__             : The SQL data type the application variable specified in the __*variable*__ parameter should be bound as. Valid values are:

\n", + "\n", + " * `ibm_db.SQL_BINARY`   : The variable should be bound as a binary large object.\n", + " * `ibm_db.SQL_CHAR`       : The variable should be bound as fixed-length character string.\n", + " * `ibm_db.SQL_DOUBLE`   : The variable should be bound as a double-precision floating-point number.\n", + " * `ibm_db.SQL_LONG`       : The variable should be bound as a long varying-length character string.

\n", + "\n", + "* __*precision*__           : The precision (i.e., total number of digits) of the application variable used. \n", + "* __*scale*__                  : The scale (i.e., number of decimal digits) of the application variable used.\n", + "* __*size*__                    : The size of the memory buffer used to store the value associated with the parameter marker. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : The bind operation was successfull. \n", + "* `False`    : The bind operation failed." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.bind_param()__ API is used to associate (bind) parameter markers in an SQL statement to application variables - a parameter marker is represented by a question mark character (?) and is used to indicate the position in an SQL statement where an application-supplied value is to be substituted when the statement is executed.

\n", + " \n", + "This API gives you more control over the parameter type (inout, output, or input/output), SQL data type, precision, and scale that is used for parameter marker values as opposed to passing values via an input tuple when the __ibm_db.execute()__ API is used." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Preparing the SQL statement \"SELECT projname FROM project WHERE deptno = ?\" ... Done!\n", + "\n", + "Processing query 1:\n", + " Binding the appropriate variable to the parameter marker used ... Done!\n", + " Executing the prepared SQL statement (with the value 'B01') ... Done!\n", + "Results:\n", + "\n", + "DEPTNO PROJNAME\n", + "______ _____________________\n", + "B01 WELD LINE PLANNING\n", + "\n", + "Processing query 2:\n", + " Binding the appropriate variable to the parameter marker used ... Done!\n", + " Executing the prepared SQL statement (with the value 'C01') ... Done!\n", + "Results:\n", + "\n", + "DEPTNO PROJNAME\n", + "______ _____________________\n", + "C01 QUERY SERVICES\n", + "C01 USER EDUCATION\n", + "\n", + "Processing query 3:\n", + " Binding the appropriate variable to the parameter marker used ... Done!\n", + " Executing the prepared SQL statement (with the value 'D01') ... Done!\n", + "Results:\n", + "\n", + "DEPTNO PROJNAME\n", + "______ _____________________\n", + "D01 ADMIN SERVICES\n", + "D01 WELD LINE AUTOMATION\n", + "\n", + "Processing query 4:\n", + " Binding the appropriate variable to the parameter marker used ... Done!\n", + " Executing the prepared SQL statement (with the value 'E01') ... Done!\n", + "Results:\n", + "\n", + "DEPTNO PROJNAME\n", + "______ _____________________\n", + "E01 OPERATION SUPPORT\n", + "E01 GEN SYSTEMS SERVICES\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-bind_param.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.bind_param() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.prepare() #\n", + "# ibm_db.execute() #\n", + "# ibm_db.fetch_tuple() #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.active() API. #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "preparedStmt = None\n", + "deptID = ['B01', 'C01', 'D01', 'E01']\n", + "returnCode = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed - Include A Parameter Marker\n", + "sqlStatement = \"SELECT projname FROM project WHERE deptno = ?\"\n", + "\n", + "# Prepare The SQL Statement Just Defined\n", + "print(\"Preparing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit\n", + "if preparedStmt is False:\n", + " print(\"\\nERROR: Unable to prepare the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# For Every Value Specified In The deptID List, ...\n", + "for loopCounter in range(0, 4):\n", + "\n", + " # Display A Message That Identifies The Query Being Executed\n", + " print(\"Processing query \" + str(loopCounter + 1) + \":\")\n", + "\n", + " # Assign A Value To The Application Variable That Is To Be Bound To The SQL Statement\n", + " paramValue = deptID[loopCounter]\n", + "\n", + " # Bind The Application Variable To The Parameter Marker Used In The SQL Statement \n", + " print(\" Binding the appropriate variable to the parameter marker used ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.bind_param(preparedStmt, 1, paramValue, ibm_db.SQL_PARAM_INPUT,\n", + " ibm_db.SQL_CHAR)\n", + " except Exception:\n", + " pass\n", + " \n", + " # If The Application Variable Was Not Bound Successfully, Display An Error Message And Exit\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to bind the variable to the parameter marker specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\")\n", + "\n", + " # Execute The Prepared SQL Statement (Using The New Parameter Marker Value)\n", + " print(\" Executing the prepared SQL statement \", end=\"\")\n", + " print(\"(with the value \\'\" + paramValue + \"\\') ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.execute(preparedStmt)\n", + " except Exception:\n", + " pass\n", + " \n", + " # If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\")\n", + "\n", + " # Display A Report Header\n", + " print(\"Results:\\n\")\n", + " print(\"DEPTNO PROJNAME\")\n", + " print(\"______ _____________________\")\n", + "\n", + " # As Long As There Are Records, ...\n", + " noData = False\n", + " while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Tuple\n", + " try:\n", + " dataRecord = ibm_db.fetch_tuple(preparedStmt)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Continue \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Format And Display The Data Retrieved\n", + " else:\n", + " print(\"{:<6} {}\" .format(paramValue, dataRecord[0])) \n", + "\n", + " # Add A Blank Line To The End Of The Report\n", + " print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-callproc.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-callproc.ipynb new file mode 100644 index 0000000..5462061 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-callproc.ipynb @@ -0,0 +1,325 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.callproc()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Call (execute) a stored procedure." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`[IBM_DBStatement | tuple] ibm_db.callproc( IBM_DBConnection `*`connection,`*` string `*`procName,`*`[, tuple `*`procParams`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__     : A valid Db2 database connection.\n", + "* __*procName*__       : The name of a stored procedure that exists in the connected database.\n", + "* __*procParams*__    : A tuple containing values (or value placeholders) for each parameter required by the procedure." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an `IBM_DBStatement` object *or* a tuple containing an `IBM_DBStatement` object, followed by the parameter values that were supplied for the __*procPrams*__ parameter.\n", + "* If __unsuccessful__, the value `None`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.callproc()__ API is used to execute a stored procedure that has been defined in the database the application is currently connected to. If the stored procedure expects __IN__, __OUT__, and/or __INOUT__ parameter values, a tuple that contains a value for each parameter defined must be supplied (via the __procParams__ parameter).

\n", + " \n", + "Upon successful execution of the procedure invoked, a tuple containing an `IBM_DBStatement` object and a modified copy of the parameter values supplied is returned. Values for __IN__ parameters are left untouched whereas values for __OUT__ and __INOUT__ parameters may have been changed by the procedure. (If the procedure did not have any parameters defined, only an `IBM_DBStatement` object will be returned.)

\n", + "\n", + "A call to a stored procedure can return zero or more result sets; if a result set is returned, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Creating an SQL stored procedure named \"SALARY_STATS\" ... Done!\n", + "\n", + "Executing the SALARY_STATS stored procedure ... Done!\n", + "\n", + "Salary statistics:\n", + "______________________________\n", + "Highest salary : $ 152750.00\n", + "Lowest salary : $ 31840.00\n", + "Average salary : $ 58155.36\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-callproc.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.callproc() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "spName = \"SALARY_STATS\"\n", + "returnCode = False\n", + "spParamValues = (0.0, 0.0, 0.0)\n", + "resultSet = None\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Used To Create A New Stored Procedure\n", + "sqlStatement = \"CREATE OR REPLACE PROCEDURE \" + spName\n", + "sqlStatement += \" (OUT maxSalary DOUBLE, OUT minSalary DOUBLE, OUT avgSalary DOUBLE) \"\n", + "sqlStatement += \"LANGUAGE SQL \"\n", + "sqlStatement += \"DYNAMIC RESULT SETS 0 \"\n", + "sqlStatement += \"READS SQL DATA \"\n", + "sqlStatement += \"NO EXTERNAL ACTION \"\n", + "sqlStatement += \"BEGIN\"\n", + "sqlStatement += \" SELECT MAX(salary) INTO maxSalary FROM employee; \"\n", + "sqlStatement += \" SELECT MIN(salary) INTO minSalary FROM employee; \"\n", + "sqlStatement += \" SELECT AVG(salary) INTO avgSalary FROM employee; \"\n", + "sqlStatement += \"END\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Creating an SQL stored procedure named \\\"\" + spName + \"\\\" ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Execute The Stored Procedure Just Created\n", + "print(\"Executing the \" + spName + \" stored procedure ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.callproc(dbConnection, spName, spParamValues)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Stored Procedure Specified Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is None:\n", + " print(\"\\nERROR: Unable to execute the stored procedure specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message; Then Format And Display The Data Values Returned\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + " # Display A Report Header\n", + " print(\"Salary statistics:\")\n", + " print(\"______________________________\")\n", + "\n", + " # Display The Data Values Returned By The Stored Procedure\n", + " print(\"Highest salary : ${:>10.2f}\" .format(resultSet[1]))\n", + " print(\"Lowest salary : ${:>10.2f}\" .format(resultSet[2]))\n", + " print(\"Average salary : ${:>10.2f}\" .format(resultSet[3]))\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-client_info.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-client_info.ipynb new file mode 100644 index 0000000..1548a4a --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-client_info.ipynb @@ -0,0 +1,303 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.client_info()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Obtain information about an IBM Db2 client." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`PyTypeObject ibm_db.client_info( IBM_DBConnection `*`connection`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 client/server connection." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, a PyTypeObject populated with the following information:

\n", + "\n", + " * `APPL_CODEPAGE`                 : The application code page used.\n", + " * `CONN_CODEPAGE`                 : The code page used for the current connection.\n", + " * `DATA_SOURCE_NAME`           : The data source name (DSN) used to create the current connection.\n", + " * `DRIVER_NAME`                     : The name of the library that implements Db2 Call Level Interface (CLI) functionality.\n", + " * `DRIVER_ODBC_VER`             : The version of Open Database Connectivity (ODBC) the client supports.\n", + " * `DRIVER_VER`                       : The version of the Db2 client software that is running on the connected workstation, in the form of a string that has the format __VV.RR.MMFF__, where __VV__ is the major version number, __RR__ is the release number, __MM__ is the modification number, and __FF__ is the fix pack number. For example, \"11.01.0404\" represents version 11, release 1, modification 4, fix pack 4.\n", + " * `ODBC_SQL_CONFORMANCE`   : The type of ODBC SQL grammar the client supports. Valid values are:

\n", + " * `MINIMAL`   : The client supports the minimum amount of ODBC SQL grammar.\n", + " * `CORE`         : The client supports the core ODBC SQL grammar.\n", + " * `EXTENDED` : The client supports extended ODBC SQL grammar.

\n", + " * `ODBC_VER`                           : The version of ODBC that the ODBC driver supports.

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.client_info()__ API is used to obtain basic information about an IBM Db2 database client workstation." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the ibm-UDOO-x86 server ... Done!\n", + "\n", + "Obtaining information about the Db2 client ... Done!\n", + "\n", + "Client details:\n", + "____________________________________________________________________\n", + "Application code page : 1208\n", + "Current connection code page : 1208\n", + "Data source name (DSN) : SAMPLE\n", + "Driver name : libdb2.a\n", + "Driver version : 11.01.0404\n", + "ODBC version supported : 03.51\n", + "ODBC SQL conformance level : Supports extended ODBC SQL grammar\n", + "\n", + "Disconnecting from the ibm-UDOO-x86 server ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-client_info.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.client_info() API. #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "svrConnection = None\n", + "clientInfo = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server\n", + "conn = Db2ConnectionMgr('SERVER', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " svrConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Obtain Information About The Db2 Client Being Used\n", + "print(\"Obtaining information about the Db2 client ... \", end=\"\")\n", + "try:\n", + " clientInfo = ibm_db.client_info(svrConnection)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If Information About The Client Could Not Be Obtained, Display An Error Message \n", + "if clientInfo is False:\n", + " print(\"\\nERROR: Unable to obtain Db2 client information.\\n\")\n", + "\n", + "# Otherwise, Complete The Status Message; Then Format And Display The Data Retrieved\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + " # Display A Report Header\n", + " print(\"Client details:\")\n", + " print(\"____________________________________________________________________\")\n", + "\n", + " # Display The Client Data\n", + " print(\"Application code page : {}\" .format(clientInfo.APPL_CODEPAGE))\n", + " print(\"Current connection code page : {}\" .format(clientInfo.CONN_CODEPAGE))\n", + " print(\"Data source name (DSN) : {}\" .format(clientInfo.DATA_SOURCE_NAME))\n", + " print(\"Driver name : {}\" .format(clientInfo.DRIVER_NAME))\n", + " print(\"Driver version : {}\" .format(clientInfo.DRIVER_VER))\n", + " print(\"ODBC version supported : {}\" .format(clientInfo.DRIVER_ODBC_VER))\n", + " print(\"ODBC SQL conformance level : \", end=\"\")\n", + " if clientInfo.ODBC_SQL_CONFORMANCE == 'MINIMAL':\n", + " print(\"Supports the minimum ODBC SQL grammar\\n\")\n", + " elif clientInfo.ODBC_SQL_CONFORMANCE == 'CORE':\n", + " print(\"Supports the core ODBC SQL grammar\\n\")\n", + " elif clientInfo.ODBC_SQL_CONFORMANCE == 'EXTENDED':\n", + " print(\"Supports extended ODBC SQL grammar\\n\")\n", + "\n", + "# Close The Server Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-close.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-close.ipynb new file mode 100644 index 0000000..5c4b689 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-close.ipynb @@ -0,0 +1,273 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Close an open IBM DB2 server or database connection and if appropriate, return it to a connection pool." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.close( IBM_DBConnection `*`connection`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server or database connection." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : The Db2 server or database connection specified was closed. \n", + "* `False`    : The Db2 server or database connection specified was not closed." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.close()__ API is used to close an open Db2 server or database connection. If this API is used to close a connection that was opened by the __ibm_db.connect()__ API, the specified connection is terminated and all associated resources are returned to the server. However, if it is used to close a persistent connection that was created with the __ibm_db.pconnect()__ API, the connection is returned to a connection pool, where it can be reused by the next __ibm_db.pconnect()__ API call made.

" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the 'SAMPLE' database ... Done!\n", + "\n", + "Disconnecting from the 'SAMPLE' database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-close.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.close() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.connect() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "returnCode = False\n", + "\n", + "# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database\n", + "# Is About To Be Made\n", + "print(\"\\nConnecting to the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + "\n", + "# Construct The String That Will Be Used To Establish A Db2 Database Connection\n", + "connString = \"ATTACH=FALSE\" # Attach To A Database; Not A Server\n", + "connString += \";DATABASE=\" + dbName # Required To Connect To A Database \n", + "connString += \";PROTOCOL=TCPIP\"\n", + "connString += \";UID=\" + userID\n", + "connString += \";PWD=\" + passWord\n", + "\n", + "# Attempt To Establish A Connection To The Database Specified\n", + "try:\n", + " dbConnection = ibm_db.connect(connString, '', '')\n", + "except Exception:\n", + " pass\n", + "\n", + "# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit\n", + "if dbConnection is None:\n", + " print(\"\\nERROR: Unable to connect to the \\'\" + dbName + \"\\' database.\")\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "\n", + "# Add Additional Db2 Database-Related Processing Here ...\n", + "\n", + "\n", + "# Attempt To Close The Db2 Database Connection That Was Just Opened\n", + "if not dbConnection is None:\n", + " print(\"Disconnecting from the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.close(dbConnection)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Database Connection Was Not Closed, Display An Error Message And Exit\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + dbName + \" database.\")\n", + " exit(-1)\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-column_privileges.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-column_privileges.ipynb new file mode 100644 index 0000000..fa46e29 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-column_privileges.ipynb @@ -0,0 +1,375 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.column_privileges()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve a list of columns and their associated privileges, for a given table." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.column_privileges( IBM_DBConnection `*`connection`*`[, string `*`qualifierName`*` [, string `*`schemaName`*` [, string `*`tableName`*` [, string `*`columnName`*` ] ] ] ] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__        : A valid Db2 server or database connection. \n", + "* __qualifierName__    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value `None` or an empty string (`''`) for Db2 databases on other operating systems. \n", + "* __schemaName__     : The name of the schema that contains the table(s) that column privilege information is to be obtained for. To match all schemas, provide the value `None` or an empty string. \n", + "* __tableName__          : The name of the table(s) and/or view(s) that column privilege information is to be obtained for. To match all tables and views, provide the value `None` or an empty string. \n", + "* __columnName__      : The name of the column that privilege information is to be obtained for. To match all columns, provide the value `None` or an empty string." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an IBM_DBStatement with a result set that contains the following information:

\n", + "\n", + " * `TABLE_CAT`        : The name of the catalog associated with the schema and table the column privilege is for; Db2 does not use catalogs so this field will always contain the value `None`. *(Db2 databases on OS/390 or z/OS servers can return information in this field.)*\n", + " * `TABLE_SCHEM`    : The name of the schema for the table or view the privilege is associated with.\n", + " * `TABLE_NAME`      : The name of the table or view the privilege is associated with.\n", + " * `COLUMN_NAME`    : The name of the column the privilege is associated with.\n", + " * `PRIVILEGE`        : The column privilege (`INSERT`, `UPDATE`, `DELETE`, `SELECT`, etc.).\n", + " * `GRANTOR`            : The authorization ID of the user who granted the privilege.\n", + " * `GRANTEE`            : The authorization ID of the user to whom the privilege was granted.\n", + " * `IS_GRANTABLE`  : Indication of whether the authorization ID of the user to whom the privilege was granted (the __GRANTEE__) is permitted to grant the privilege to others. Valid values are `YES` and `NO`.

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.column_privileges()__ API is used to retrieve a list of columns and the privileges associated with them, for one or more tables and/or views.

\n", + "\n", + "The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Obtaining information about column privileges that exist for the PROJNO column\n", + "of the DB2INST1.PROJECT table ... Done!\n", + "\n", + "Column privilege 1 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Column name : PROJNO\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : INSERT\n", + "Privilege is grantable : YES\n", + "\n", + "Column privilege 2 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Column name : PROJNO\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : REFERENCES\n", + "Privilege is grantable : YES\n", + "\n", + "Column privilege 3 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Column name : PROJNO\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : SELECT\n", + "Privilege is grantable : YES\n", + "\n", + "Column privilege 4 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Column name : PROJNO\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : UPDATE\n", + "Privilege is grantable : YES\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-column_privileges.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.column_privileges() #\n", + "# API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.fetch_assoc() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "schemaName = userID.upper()\n", + "tableName = \"PROJECT\"\n", + "columnName = \"PROJNO\"\n", + "resultSet = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Retrieve Information About All Of The Column Privileges That Have Been Defined For \n", + "# The Table Specified\n", + "print(\"Obtaining information about column privileges that exist for the \" + columnName, end=\"\")\n", + "print(\" column\\nof the \" +schemaName + \".\" + tableName + \" table ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.column_privileges(dbConnection, None, schemaName, tableName, columnName)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit\n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# As Long As There Are Records (That Were Produced By The ibm_db.column_privileges API), ... \n", + "noData = False\n", + "loopCounter = 1\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Information Retrieved\n", + " else:\n", + "\n", + " #--------------------------------------------------------------------------------------#\n", + " # NOTE: The column name parameter value specified with the ibm_db.column_privileges() #\n", + " # API appears to be ignored; if you only want to see column privilege information for #\n", + " # a specific column, you will need to use the following filtering code: #\n", + " if dataRecord['COLUMN_NAME'] != columnName:\n", + " continue\n", + " #--------------------------------------------------------------------------------------#\n", + "\n", + " # Display Record Header Information\n", + " print(\"Column privilege \" + str(loopCounter) + \" details:\")\n", + " print(\"___________________________________\")\n", + "\n", + " # Display The Information Stored In The Data Record Retrieved\n", + " print(\"Schema name : {}\" .format(dataRecord['TABLE_SCHEM']))\n", + " print(\"Table name : {}\" .format(dataRecord['TABLE_NAME']))\n", + " print(\"Column name : {}\" .format(dataRecord['COLUMN_NAME']))\n", + " print(\"Privilege grantor : {}\" .format(dataRecord['GRANTOR']))\n", + " print(\"Privilege recipient : {}\" .format(dataRecord['GRANTEE']))\n", + " print(\"Privilege : {}\" .format(dataRecord['PRIVILEGE']))\n", + " print(\"Privilege is grantable : {}\" .format(dataRecord['IS_GRANTABLE']))\n", + "\n", + " # Increment The loopCounter Variable And Print A Blank Line To Separate Column The\n", + " # Records From Each Other\n", + " loopCounter += 1\n", + " print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-columns.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-columns.ipynb new file mode 100644 index 0000000..afe6c15 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-columns.ipynb @@ -0,0 +1,435 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.columns()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve a list of columns and their associated metadata, for a given table." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.columns( IBM_DBConnection `*`connection`*` [, string `*`qualifierName`*` [, string `*`schemaName`*` [, string `*`tableName`*` [, string `*`columnName`*`] ] ] ] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__        : A valid Db2 server or database connection. \n", + "* __qualifierName__    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value `None` or an empty string (`''`) for Db2 databases on other operating systems. \n", + "* __schemaName__     : The name of the schema that contains the table(s) that column information is to be obtained for. To match all schemas, provide the value `None` or an empty string. \n", + "* __tableName__          : The name of the table(s) and/or view(s) that column information is to be obtained for. To match all tables and views, provide the value `None` or an empty string. \n", + "* __columnName__      : The name of the column that information is to be obtained for. To match all columns, provide the value `None` or an empty string." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an `IBM_DBStatement` object with a result set that contains the following information:

\n", + "\n", + " * `TABLE_CAT`                     : The name of the catalog associated with the schema and table the column is in; Db2 does not use catalogs so this field will always contain the value `None`. *(Db2 databases on OS/390 or z/OS servers can return information in this field.)*\n", + " * `TABLE_SCHEM`                 : The name of the schema for the table or view the column is associated with.\n", + " * `TABLE_NAME`                   : The name of the table or view the column is associated with.\n", + " * `COLUMN_NAME`                 : The name of the column.\n", + " * `DATA_TYPE`                     : An integer value that represents the SQL data type of the column. (On Linux and UNIX systems, valid values for this field can be found in the file */opt/ibm/db2/V11.1/include/sqlcli.h*.)\n", + " * `TYPE_NAME`                     : The data source-specific string representation of the SQL data type of the column.\n", + " * `COLUMN_SIZE`                 : The number of bytes needed to display the column's data as a string.\n", + " * `BUFFER_LENGTH`             : The number of bytes needed to store the column's data in an application variable. \n", + " * `DECIMAL_DIGITS`           : The scale (i.e., total number of significant digits to the right of the decimal point) of the column - provided the column has a numerical data type. If the column does not have a numerical data type, this field will contain the value `None`.\n", + " * `NUM_PREC_RADIX`           : A numerical value that indicates whether the column's data type represents an exact numeric data type (`10`) or an approximate numeric data type (`2`). If the column does not have a numerical data type, this field will contain the value `None`.\n", + " * `NULLABLE`                       : Indication of whether the column accepts a __NULL__ value; `ibm_db.SQL_YES` will be returned if __NULL__ values are accepted and `ibm_db.SQL_NO` will be returned if they are not.\n", + " * `REMARKS`                         : A user-supplied description of the column (if one has been provided).\n", + " * `COLUMN_DEF`                   : The default value for the column (if one has been defined).\n", + " * `SQL_DATA_TYPE`             : An integer value that represents the SQL data type of the column, as it would appear in a row descriptor record. In most cases, this will be the same as the value provided in the __DATA_TYPE__ field. (On Linux and UNIX systems, valid values for this field can be found in the file */opt/ibm/db2/V11.1/include/sqlcli.h*.)\n", + " * `SQL_DATETIME_SUB`       : An integer value that represents the SQL date/time subtype code for the column - provided the column has a date, time, or timestamp data type. If the column does not have one of these data types, this field will contain the value `None`. (On Linux and UNIX systems, valid values for this field can be found in the file */opt/ibm/db2/V11.1/include/sqlcli.h*.)\n", + " * `CHAR_OCTECT_LENGTH`   : The length, in octets (8-bit bytes), needed to display the column's data as a string. (This will be the same as the __COLUMN_SIZE__ value for single-byte character set data.) If the column does not have a character data type, this field will contain the value `None`.\n", + " * `ORDINAL_POSITION`       : The column's ordinal position in the table, starting from 1.\n", + " * `IS_NULLABLE`                 : Indication of whether the column can contain __NULL__ values, according to the rules in the ISO SQL92 standard. This field will contain the value `\"YES\"` if the column can contain __NULL__ values and the value `\"NO\"` if it cannot.

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.columns()__ API is used to retrieve a list of columns and their associated metadata, for one or more tables and/or views.

\n", + "\n", + "The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Obtaining information about columns that have been defined for the ACT table ... Done!\n", + "\n", + "Column 1 details:\n", + "_________________________________________\n", + "Table schema : DB2INST1\n", + "Table name : ACT\n", + "Column name : ACTNO\n", + "Data type : SMALLINT\n", + "Size : 5\n", + "Buffer size : 2\n", + "Scale (decimal digits) : 0\n", + "Precision radix : Exact numeric data type\n", + "Can accept NULL values : NO\n", + "Remarks : None\n", + "Default value : None\n", + "SQL data type : SQL_SMALLINT\n", + "SQL data/time subtype : None\n", + "Data type : 5\n", + "Length in octets : Not applicable\n", + "Ordinal position : 1\n", + "Can contain NULL values : NO\n", + "\n", + "Column 2 details:\n", + "_________________________________________\n", + "Table schema : DB2INST1\n", + "Table name : ACT\n", + "Column name : ACTKWD\n", + "Data type : CHAR\n", + "Size : 6\n", + "Buffer size : 6\n", + "Scale (decimal digits) : Not applicable\n", + "Precision radix : Not applicable\n", + "Can accept NULL values : NO\n", + "Remarks : None\n", + "Default value : None\n", + "SQL data type : SQL_CHAR\n", + "SQL data/time subtype : None\n", + "Data type : 1\n", + "Length in octets : 6\n", + "Ordinal position : 2\n", + "Can contain NULL values : NO\n", + "\n", + "Column 3 details:\n", + "_________________________________________\n", + "Table schema : DB2INST1\n", + "Table name : ACT\n", + "Column name : ACTDESC\n", + "Data type : VARCHAR\n", + "Size : 20\n", + "Buffer size : 20\n", + "Scale (decimal digits) : Not applicable\n", + "Precision radix : Not applicable\n", + "Can accept NULL values : NO\n", + "Remarks : None\n", + "Default value : None\n", + "SQL data type : SQL_VARCHAR\n", + "SQL data/time subtype : None\n", + "Data type : 12\n", + "Length in octets : 20\n", + "Ordinal position : 3\n", + "Can contain NULL values : NO\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-columns.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.columns() #\n", + "# API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.fetch_assoc() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "tableName = \"ACT\"\n", + "resultSet = False\n", + "dataRecord = False\n", + "sqlDataTypes = {0 : \"SQL_UNKNOWN_TYPE\", 1 : \"SQL_CHAR\", 2 : \"SQL_NUMERIC\", 3 : \"SQL_DECIMAL\",\n", + " 4 : \"SQL_INTEGER\", 5 : \"SQL_SMALLINT\", 6 : \"SQL_FLOAT\", 7 : \"SQL_REAL\", 8 : \"SQL_DOUBLE\",\n", + " 9 : \"SQL_DATETIME\", 12 : \"SQL_VARCHAR\", 16 : \"SQL_BOOLEAN\", 19 : \"SQL_ROW\", \n", + " 91 : \"SQL_TYPE_DATE\", 92 : \"SQL_TYPE_TIME\", 93 : \"SQL_TYPE_TIMESTAMP\",\n", + " 95 : \"SQL_TYPE_TIMESTAMP_WITH_TIMEZONE\", -8 : \"SQL_WCHAR\", -9 : \"SQL_WVARCHAR\",\n", + " -10 : \"SQL_WLONGVARCHAR\", -95 : \"SQL_GRAPHIC\", -96 : \"SQL_VARGRAPHIC\",\n", + " -97 : \"SQL_LONGVARGRAPHIC\", -98 : \"SQL_BLOB\", -99 : \"SQL_CLOB\", -350 : \"SQL_DBCLOB\",\n", + " -360 : \"SQL_DECFLOAT\", -370 : \"SQL_XML\", -380 : \"SQL_CURSORHANDLE\", -400 : \"SQL_DATALINK\",\n", + " -450 : \"SQL_USER_DEFINED_TYPE\"}\n", + "sqlDateTimeSubtypes = {1 : \"SQL_CODE_DATE\", 2 : \"SQL_CODE_TIME\", 3 : \"SQL_CODE_TIMESTAMP\",\n", + " 4 : \"SQL_CODE_TIMESTAMP_WITH_TIMEZONE\"}\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Retrieve Information About All Of The Columns That Have Been Defined For\n", + "# A Particular Table\n", + "print(\"Obtaining information about columns that have been defined for the \", end=\"\")\n", + "print(tableName + \" table ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.columns(dbConnection, None, None, tableName, None)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit\n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired\\n.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# As Long As There Are Records (That Were Produced By The ibm_db.columns API), ...\n", + "noData = False\n", + "loopCounter = 1\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Information Retrieved\n", + " else:\n", + "\n", + " # Display Record Header Information\n", + " print(\"Column \" + str(loopCounter) + \" details:\")\n", + " print(\"_________________________________________\")\n", + "\n", + " # Display The Information Stored In The Data Record Retrieved\n", + " print(\"Table schema : {}\" .format(dataRecord['TABLE_SCHEM']))\n", + " print(\"Table name : {}\" .format(dataRecord['TABLE_NAME']))\n", + " print(\"Column name : {}\" .format(dataRecord['COLUMN_NAME']))\n", + " print(\"Data type : {}\" .format(dataRecord['TYPE_NAME']))\n", + " print(\"Size : {}\" .format(dataRecord['COLUMN_SIZE']))\n", + " print(\"Buffer size : {}\" .format(dataRecord['BUFFER_LENGTH']))\n", + " print(\"Scale (decimal digits) : \", end=\"\")\n", + " if dataRecord['DECIMAL_DIGITS'] == None:\n", + " print(\"Not applicable\")\n", + " else:\n", + " print(\"{}\" .format(dataRecord['DECIMAL_DIGITS']))\n", + " print(\"Precision radix : \", end=\"\")\n", + " if dataRecord['NUM_PREC_RADIX'] == 10:\n", + " print(\"Exact numeric data type\")\n", + " elif dataRecord['NUM_PREC_RADIX'] == 2:\n", + " print(\"Approximate numeric data type\")\n", + " elif dataRecord['NUM_PREC_RADIX'] == None:\n", + " print(\"Not applicable\")\n", + " print(\"Can accept NULL values : \", end=\"\")\n", + " if dataRecord['NULLABLE'] == ibm_db.SQL_FALSE:\n", + " print(\"NO\")\n", + " elif dataRecord['NULLABLE'] == ibm_db.SQL_TRUE:\n", + " print(\"YES\")\n", + " print(\"Remarks : {}\" .format(dataRecord['REMARKS']))\n", + " print(\"Default value : {}\" .format(dataRecord['COLUMN_DEF']))\n", + " print(\"SQL data type : \", end=\"\")\n", + " print(sqlDataTypes.get(dataRecord['SQL_DATA_TYPE']))\n", + " print(\"SQL data/time subtype : \", end=\"\")\n", + " print(sqlDateTimeSubtypes.get(dataRecord['SQL_DATETIME_SUB']))\n", + " print(\"Data type : {}\" .format(dataRecord['DATA_TYPE']))\n", + " print(\"Length in octets : \", end=\"\")\n", + " if dataRecord['CHAR_OCTET_LENGTH'] == None:\n", + " print(\"Not applicable\")\n", + " else:\n", + " print(\"{}\" .format(dataRecord['CHAR_OCTET_LENGTH']))\n", + " print(\"Ordinal position : {}\" .format(dataRecord['ORDINAL_POSITION']))\n", + " print(\"Can contain NULL values : {}\" .format(dataRecord['IS_NULLABLE']))\n", + "\n", + " # Increment The loopCounter Variable And Print A Blank Line To Separate The\n", + " # Records From Each Other\n", + " loopCounter += 1\n", + " print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-commit.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-commit.ipynb new file mode 100644 index 0000000..5764270 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-commit.ipynb @@ -0,0 +1,344 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.commit()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Terminate an in-progress transaction and make the effects of all operations performed within the transaction permanent." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.commit( IBM_DBConnection `*`connection`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server or database connection." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : Changes made by the current transaction were made permanent (committed). \n", + "* `False`    : Changes made by the current transaction were not committed." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.commit()__ API is used to terminate an in-progress transaction and apply all changes that were made by that transaction to the database. (A *transaction* is a sequence of one or more SQL operations that are grouped together as a single process; when a transaction is committed, the effects of all operations that were performed by the transaction are made permanent.) Normally, a transaction is initiated the first time an SQL statement is executed after a database connection is established or an in-progress transaction ends. But, with Python applications, each SQL operation is treated as a transaction that is implicitly committed as soon as it completes unless __AUTOCOMMIT__ behavior is turned __OFF__. Consequently, the __ibm_db.commit()__ API has no effect when __AUTOCOMMIT__ behavior is __ON__ (the default).

\n", + "\n", + "It is important to note that if the connection being used is a persistent connection (i.e., a connection that was established with the __ibm_db.pconnect()__ API), in-progress transactions for *all applications using the connection will be rolled back when this API is called*. For this reason, the use of persistent connections is not recommended for applications that need to control transaction boundaries." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Turning AUTOCOMMIT behavior OFF ... Done!\n", + "\n", + "Number of records found in the DEPARTMENT table: 14\n", + "\n", + "Inserting a record into the DEPARTMENT table ... Done!\n", + "\n", + "Number of records found in the DEPARTMENT table: 15\n", + "\n", + "Commiting changes made to the database ... Done!\n", + "\n", + "Number of records found in the DEPARTMENT table: 15\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-commit.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.commit() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.autocommit() #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.stmt_errormsg() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The get_row_count() Function That Has Been Defined In The File Named #\n", + "# \"ibm_db_tools.py\"; This Function Contains The Programming Logic Needed To Obtain And #\n", + "# Display The Number Of Rows (Records) Found In A Db2 Database Table #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import get_row_count\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "returnCode = False\n", + "resultSet = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Turn Autocommit Behavior OFF\n", + "print(\"Turning AUTOCOMMIT behavior OFF ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_OFF)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If AUTOCOMMIT Behavior Could Not Be Turned OFF, Display An Error Message And Continue\n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to turn AUTOCOMMIT behavior OFF.\")\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table\n", + "returnCode = get_row_count(dbConnection, 'DEPARTMENT')\n", + "if returnCode is False:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The INSERT Statement That Is To Be Used To Add Data To The DEPARTMENT Table\n", + "sqlStatement = \"INSERT INTO department VALUES('K01', 'SALES', '000130', 'K01', NULL)\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Inserting a record into the DEPARTMENT table ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the INSERT statement specified.\")\n", + " errorMsg = ibm_db.stmt_errormsg()\n", + " print(\"\\n\" + errorMsg + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display The Number Of Rows That Exist In The DEPARTMENT Table Now\n", + "# (The Number Returned Should Change)\n", + "returnCode = get_row_count(dbConnection, 'DEPARTMENT')\n", + "if returnCode is False:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Commit The Changes Just Made (To Make Them Permanent)\n", + "print(\"Commiting changes made to the database ... \", end=\"\")\n", + "resultSet = False\n", + "try:\n", + " resultSet = ibm_db.commit(dbConnection)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Commit Operation Could Not Be Performed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to commit the previous operation.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display The Number Of Rows That Exist In The DEPARTMENT Table Now\n", + "# (The Number Should Not Change)\n", + "returnCode = get_row_count(dbConnection, 'DEPARTMENT')\n", + "if returnCode is False:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-conn_error.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-conn_error.ipynb new file mode 100644 index 0000000..3bc51bb --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-conn_error.ipynb @@ -0,0 +1,302 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.conn_error()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Return an SQLSTATE value associated with an `IBM_DBConnection` object." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`string ibm_db.conn_error( [ IBM_DBConnection `*`connection`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server or database connection." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*connection*__ value is provided: \n", + "* If there is an __error__ associated with the Db2 server or database connection specified, a string containing an SQLSTATE value that explains why the last operation using the `IBM_DBConnection` object failed.\n", + "* If there is __no error__ associated with the Db2 server or database connection specified, an empty string (`''`)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*connection*__ value is not provided: \n", + "* If there is an __error__ associated with the last attempt to return an `IBM_DBConnection` object from an __ibm_db.connect()__ or __ibm_db.pconnect__ API, a string containing an SQLSTATE value that explains why the API failed.\n", + "* If there is __no error__ associated with the last attempt to return an `IBM_DBConnection` object, an empty string (`''`)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.conn_error()__ API can be used to return an SQLSTATE value that explains why an attempt to establish a Db2 server or database connection (using the __ibm_db.connect()__ or __ibm_db.pconnect()__ API) was not successful. It can also be used to return an SQLSTATE value that identifies why the last operation using a `IBM_DBConnection` object failed." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the 'SAMPLE' database ... \n", + "ERROR: Unable to connect to the 'SAMPLE' database.\n", + "\n", + "SQLSTATE: 08001\n", + "\n" + ] + }, + { + "ename": "ipynb_Exit", + "evalue": "", + "output_type": "error", + "traceback": [ + "An exception has occurred, use %tb to see the full traceback.\n", + "\u001b[0;31mipynb_Exit\u001b[0m\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-conn_error.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.conn_error() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.connect() #\n", + "# ibm_db.close() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw_rd\" # The Wrong Password Is Used To Force An Error To Occur\n", + "dbConnection = None\n", + "\n", + "# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database\n", + "# Is About To Be Made\n", + "print(\"\\nConnecting to the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + "\n", + "# Construct The String That Will Be Used To Establish A Db2 Database Connection\n", + "connString = \"ATTACH=FALSE\" # Attach To A Database; Not A Server\n", + "connString += \";DATABASE=\" + dbName # Required To Connect To A Database \n", + "connString += \";PROTOCOL=TCPIP\"\n", + "connString += \";UID=\" + userID\n", + "connString += \";PWD=\" + passWord\n", + "\n", + "# Attempt To Establish A Connection To The Database Specified\n", + "try:\n", + " dbConnection = ibm_db.connect(connString, '', '')\n", + "except Exception:\n", + " pass\n", + "\n", + "# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit\n", + "if dbConnection is None:\n", + " print(\"\\nERROR: Unable to connect to the \\'\" + dbName + \"\\' database.\")\n", + " errorCode = ibm_db.conn_error()\n", + " print(\"\\nSQLSTATE: \"+ errorCode + \"\\n\")\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "\n", + "# Add Additional Db2 Database-Related Processing Here ...\n", + "\n", + "\n", + "# Attempt To Close The Db2 Database Connection That Was Just Opened\n", + "if not dbConnection is None:\n", + " print(\"Disconnecting from the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.close(dbConnection)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + dbName + \" database.\")\n", + " errorCode = ibm_db.conn_error(dbConnection)\n", + " print(\"SQLSTATE: \"+ errorCode + \"\\n\")\n", + " exit(-1)\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-conn_errormsg.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-conn_errormsg.ipynb new file mode 100644 index 0000000..efe1352 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-conn_errormsg.ipynb @@ -0,0 +1,302 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.conn_errormsg()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Return an SQLCODE and corresponding error message associated with an `IBM_DBConnection` object." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`string ibm_db.conn_errormsg( [ IBM_DBConnection `*`connection`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server or database connection." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return codes:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*connection*__ value is provided: \n", + "* If there is an __error__ associated with the Db2 server or database connection specified, a string containing an SQLCODE and corresponding error message that explains why the last operation using the `IBM_DBConnection` object failed.\n", + "* If there is __no error__ associated with the Db2 server or database connection specified, an empty string (`''`)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*connection*__ value is not provided: \n", + "* If there is an __error__ associated with the last attempt to return an `IBM_DBConnection` object from an __ibm_db.connect()__ or __ibm_db.pconnect__ API, a string containing an SQLCODE and corresponding error message that explains why the API failed.\n", + "* If there is __no error__ associated with the last attempt to return an `IBM_DBConnection` object, an empty string (`''`)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.conn_errormsg()__ API can be used to return an SQLCODE and corresponding error message that explains why an attempt to establish a Db2 server or database connection (using the __ibm_db.connect()__ or __ibm_db.pconnect()__ API) was not successful. It can also be used to return an SQLCODE and error message that identifies why the last operation using a `IBM_DBConnection` object failed." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the 'SAMPLE' database ... \n", + "ERROR: Unable to connect to the 'SAMPLE' database.\n", + "\n", + "[IBM][CLI Driver] SQL30082N Security processing failed with reason \"24\" (\"USERNAME AND/OR PASSWORD INVALID\"). SQLSTATE=08001 SQLCODE=-30082\n", + "\n" + ] + }, + { + "ename": "ipynb_Exit", + "evalue": "", + "output_type": "error", + "traceback": [ + "An exception has occurred, use %tb to see the full traceback.\n", + "\u001b[0;31mipynb_Exit\u001b[0m\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-conn_errormsg.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.conn_errormsg() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.connect() #\n", + "# ibm_db.close() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw_rd\" # The Wrong Password Is Used To Force An Error To Occur\n", + "dbConnection = None\n", + "\n", + "# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database\n", + "# Is About To Be Made\n", + "print(\"\\nConnecting to the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + "\n", + "# Construct The String That Will Be Used To Establish A Db2 Database Connection\n", + "connString = \"ATTACH=FALSE\" # Attach To A Database; Not A Server\n", + "connString += \";DATABASE=\" + dbName # Required To Connect To A Database \n", + "connString += \";PROTOCOL=TCPIP\"\n", + "connString += \";UID=\" + userID\n", + "connString += \";PWD=\" + passWord\n", + "\n", + "# Attempt To Establish A Connection To The Database Specified\n", + "try:\n", + " dbConnection = ibm_db.connect(connString, '', '')\n", + "except Exception:\n", + " pass\n", + "\n", + "# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit\n", + "if dbConnection is None:\n", + " print(\"\\nERROR: Unable to connect to the \\'\" + dbName + \"\\' database.\")\n", + " errorMsg = ibm_db.conn_errormsg()\n", + " print(\"\\n\" + errorMsg + \"\\n\")\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "\n", + "# Add Additional Db2 Database-Related Processing Here ...\n", + "\n", + "\n", + "# Attempt To Close The Db2 Database Connection That Was Just Opened\n", + "if not dbConnection is None:\n", + " print(\"Disconnecting from the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.close(dbConnection)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + dbName + \" database.\")\n", + " errorCode = ibm_db.conn_error(dbConnection)\n", + " print(\"SQLSTATE: \"+ errorCode + \"\\n\")\n", + " exit(-1)\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-connect.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-connect.ipynb new file mode 100644 index 0000000..d35a87c --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-connect.ipynb @@ -0,0 +1,470 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.connect()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Establish a new connection to an IBM Db2 server or database." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBConnection ibm_db.connect( string `*`connectionInfo,`*` string `*`userID,`*` string `*`userPassword`*` [, dictionary `*`options`*` [, constant `*`replaceQuotedLiterals`*` ] ] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connectionInfo*__                : A valid Db2 database alias (if the database has been cataloged in the system database directory) *or* a connection string with the format `DRIVER={IBM DB2 ODBC DRIVER};ATTACH=connType;DATABASE=dbName;HOSTNAME=hostName;PORT=port;PROTOCOL=TCPIP;UID=userName;PWD=password` where:

\n", + " \n", + " * `connType`     : Specifies whether the connection is to be made to a Db2 server or database; `TRUE` indicates the connection is to be made to a Db2 server and `FALSE` indicates the connection is to be made to a database.\n", + " * `dbName`         : The name of the Db2 server or database the connection is to be made to. *This option is only required when connecting to a Db2 database.*\n", + " * `hostName`     : The host name or IP address of the Db2 server the connection is to be made to. (The hostname is the name of the Db2 server, as it is known to the TCP/IP network.) *This option is only required when connecting to a Db2 server.*\n", + " * `port`             : The port number that receives Db2 connections on the server the connection is to be made to. (Port number __50000__ is used by default.) *This option is only required when connecting to a Db2 server.*\n", + " * `userName`     : The user name/ID that is to be used for authentication when the connection is established.\n", + " * `password`     : The password that corresponds to the user name/ID specified in the __*userName*__ parameter.

\n", + " \n", + "* __*userID*__                               : The user ID that is to be used for authentication when a connection is established. *If a Db2 database alias is NOT provided in the __connectionInfo__ parameter, this parameter must contain an empty string.*\n", + "* __*userPassword*__                  : The password that corresponds to the user ID specified in the __*userPassword*__ parameter. *If a Db2 database alias is NOT provided in the __connectionInfo__ parameter, this parameter must contain an empty string.* \n", + "* __*options*__                             : A dictionary containing key-value pairs for the attributes that are to be set before a connection is established. Valid keys for `IBM_DBConnection` objects are:

\n", + " \n", + " * `ibm_db.SQL_ATTR_AUTOCOMMIT`                     : Specifies whether __AUTOCOMMIT__ mode is to be used or not; `ibm_db.SQL_AUTOCOMMIT_ON` will turn __AUTOCOMMIT__ behavior __ON__ and `ibm_db.SQL_AUTOCOMMIT_OFF` will turn it __OFF__.\n", + " * `ibm_db.SQL_ATTR_CASE`                                 : The case that column names will be returned in; `ibm_db.CASE_NATURAL` will cause column names to be returned in natural case, `ibm_db.CASE_LOWER` will cause them to be returned in lower case, and `ibm_db.CASE_UPPER` will cause them to be returned in upper case. *(This attribute can only be used with Db2 databases on OS/390 or z/OS servers.)*\n", + " * `ibm_db.SQL_ATTR_CURRENT_SCHEMA`             : The name of the schema to use, by default, when performing operations that require a schema name and one is not provided.\n", + " * `ibm_db.SQL_ATTR_USE_TRUSTED_CONTEXT`   : Specifies whether the connection to a Db2 server or database is to be treated as a trusted connection; `ibm_db.SQL_TRUE` indicates the connection can be trusted and `ibm_db.SQL_FALSE` indicates the connection should not to be treated as a trusted connection.

\n", + " \n", + "* __*replaceQuotedLiterals*__    : Identifies whether quotes are allowed around literal values. Valid values for this parameter are:

\n", + " \n", + " * `ibm_db.QUOTED_LITERAL_REPLACEMENT_ON`     : Quotes cannot be used with literal values. For example, if the SQL statement __SELECT deptname FROM org WHERE deptnumb = '50000'__ is executed and the __deptnumb__ column has a numeric data type, an error will occur. (This is the default behavior.)\n", + " * `ibm_db.QUOTED_LITERAL_REPLACEMENT_OFF`   : Quotes can be used with literal values. For example, if the SQL statement __SELECT deptname FROM org WHERE deptnumb = '50000'__ is executed and the __deptnumb__ column has a numeric data type, the data requested will be returned." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, a valid `IBM_DBConnection` object.\n", + "* If __unsuccessful__, the value `None`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.connect()__ API is used to establish a new connection to an IBM Db2 server or database.

\n", + " \n", + "If a connection to a remote Db2 server or database is desired, the information needed to connect to the server (i.e., the host name, port number, and communications protocol) must be provided before a connection to either resource can be established. If a connection to a local, cataloged Db2 database is needed instead, just the alias for the database, as defined in the system database directory, must be supplied; values for the __*userID*__ and __*userPassword*__ parameters are optional. (If this API is called and just a local database alias is provided — for example, __conn = ibm_db.connect( 'SAMPLE', ' ', ' ' )__, — an attempt to establish a connection to the database will be made using the authorization ID and password for the current logged in Db2 instance user.)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Examples:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 1: Connect to a local, cataloged Db2 database" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the 'SAMPLE' database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT deptname FROM org WHERE deptnumb = '50000'\" ... Done!\n", + "\n", + "Disconnecting from the 'SAMPLE' database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-connect_DB.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.connect() API to #\n", + "# establish a connection to a local Db2 database. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.close() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\" # The Alias For The Cataloged, Local Database\n", + "userID = \"db2inst1\" # The Instance User ID At The Local Server\n", + "passWord = \"Passw0rd\" # The Password For The Instance User ID At The Local Server\n", + "connOption = {ibm_db.SQL_ATTR_AUTOCOMMIT: ibm_db.SQL_AUTOCOMMIT_ON}\n", + "connectionID = None\n", + "resultSet = False\n", + "\n", + "# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database\n", + "# Is About To Be Made\n", + "print(\"\\nConnecting to the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + "\n", + "# Construct The String That Will Be Used To Establish A Db2 Database Connection\n", + "connString = \"ATTACH=FALSE\" # Attach To A Database; Not A Server\n", + "connString += \";DATABASE=\" + dbName # Required To Connect To A Database \n", + "connString += \";PROTOCOL=TCPIP\"\n", + "connString += \";UID=\" + userID\n", + "connString += \";PWD=\" + passWord\n", + "\n", + "# Attempt To Establish A Connection To The Database Specified\n", + "try:\n", + " connectionID = ibm_db.connect(connString, '', '', connOption, \n", + " ibm_db.QUOTED_LITERAL_REPLACEMENT_OFF)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit\n", + "if connectionID is None:\n", + " print(\"\\nERROR: Unable to connect to the \\'\" + dbName + \"\\' database.\")\n", + " print(\"Connection string used: \" + connString + \"\\n\")\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + " \n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT deptname FROM org WHERE deptnumb = '50000'\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(connectionID, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " if not connectionID is None:\n", + " ibm_db.close(connectionID)\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\") \n", + " \n", + "# Attempt To Close The Db2 Database Connection That Was Opened Earlier\n", + "if not connectionID is None:\n", + " print(\"Disconnecting from the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.close(connectionID)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + dbName + \" database.\")\n", + " exit(-1)\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 2: Connect to a remote Db2 server" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the '197.126.80.22' server ... Done!\n", + "\n", + "Disconnecting from the '197.126.80.22' server ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-connect_SERVER.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.connect() API to #\n", + "# establish a connection to a remote Db2 server. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.close() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "hostName = \"197.126.80.22\" # IP Address Of Remote Server\n", + "portNum = \"50000\" # Port Number That Receives Db2 Connections On The Remote Server \n", + "userID = \"db2inst2\" # The Instance User ID At The Remote Server\n", + "passWord = \"ibmdb2\" # The Password For The Instance User ID At The Remote Server\n", + "connectionID = None\n", + "\n", + "# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Server\n", + "# Is About To Be Made\n", + "print(\"\\nConnecting to the \\'\" + hostName + \"\\' server ... \", end=\"\")\n", + " \n", + "# Construct The String That Will Be Used To Establish A Db2 Server Connection\n", + "connString = \"DRIVER={IBM DB2 ODBC DRIVER}\"\n", + "connString += \";ATTACH=TRUE\" # Attach To A Server; Not A Database\n", + "connString += \";DATABASE=\" # Ignored When Connecting To A Server\n", + "connString += \";HOSTNAME=\" + hostName # Required To Connect To A Server\n", + "connString += \";PORT=\" + portNum # Required To Connect To A Server\n", + "connString += \";PROTOCOL=TCPIP\" # Required To Connect To A Server\n", + "connString += \";UID=\" + userID\n", + "connString += \";PWD=\" + passWord\n", + "\n", + "# Attempt To Establish A Connection To The Server Specified\n", + "try:\n", + " connectionID = ibm_db.connect(connString, '', '')\n", + "except Exception:\n", + " pass\n", + "\n", + "# If A Db2 Server Connection Could Not Be Established, Display An Error Message And Exit\n", + "if connectionID is None:\n", + " print(\"\\nERROR: Unable to connect to the \\'\" + hostName + \"\\' server.\")\n", + " print(\"Connection string used: \" + connString + \"\\n\")\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "\n", + "# Add Additional Db2 Server-Related Processing Here ...\n", + "# For Example, ibm_db.createdb(), ibm_db.createdbNX(), ibm_db.recreatedb(), ibm_db.dropdb()\n", + "\n", + "\n", + "# Attempt To Close The Db2 Server Connection That Was Just Opened\n", + "if not connectionID is None:\n", + " print(\"Disconnecting from the \\'\" + hostName + \"\\' server ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.close(connectionID)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + hostName + \" server.\")\n", + " exit(-1)\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-createdb.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-createdb.ipynb new file mode 100644 index 0000000..6d1bac8 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-createdb.ipynb @@ -0,0 +1,414 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.createdb()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Create a new database using the name and code set specified." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.createdb( IBM_DBConnection `*`connection`*`, string `*`dbName`*` [, string `*`codeSet`*` ] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server connection. \n", + "* __*dbName*__         : The name to assign to the database that is to be created. \n", + "* __*codeSet*__         : The code set that is to be used for storing data that is entered into the database. If a __*codeSet*__ value is not specified, the UTF-8 (Unicode) code set is used." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : The database specified was created. \n", + "* `False`    : The database specified could not be created." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.createdb()__ API is used to create a new database and assign it the name specified. Optionally, the code set that is to be used for storing data entered into the database can also be specified when this API is executed. (The *code set* controls how unique numbers are assigned to characters in a particular character set.)

\n", + " \n", + "It's important to note that when this API is used, the name that is to be assigned to the database being created *must* be unique from all other database names in the system database or local database directory. If the name provided is the same as that of a database that already exists, an error will be generated and the database will not be created. *This is different from when the __ibm_db.createdbNX()__ API is used to create a database and the name specified matches the name of a database that already exists.*" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Examples:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 1: Create a new database at a local server" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the local server ... Done!\n", + "\n", + "Creating a database named MY_DB at the local server. Please wait.\n", + "\n", + "The database \"MY_DB\" has been created!\n", + "\n", + "Disconnecting from the local server ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-createdb_LOCAL.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.createdb() API to #\n", + "# create a local Db2 database. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.conn_errormsg() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "userID = \"db2inst1\" # User ID (Recognized By The Local Server)\n", + "passWord = \"Passw0rd\" # User Password\n", + "svrConnection = None\n", + "dbName = \"MY_DB\"\n", + "returnCode = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To The Local Db2 Server\n", + "conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " svrConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Create A New Database At The Local Server\n", + "print(\"Creating a database named \" + dbName + \" at the local server. Please wait.\")\n", + "try:\n", + " returnCode = ibm_db.createdb(svrConnection, dbName)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Database Could Not Be Created, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"ERROR: Unable to create the \" + dbName + \" database.\\n\")\n", + " errorMsg = ibm_db.conn_errormsg(svrConnection)\n", + " print(errorMsg + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + " \n", + "# Otherwise, Display A Status Message \n", + "else:\n", + " print(\"\\nThe database \\\"\" + dbName + \"\\\" has been created!\\n\")\n", + "\n", + "# Close The Db2 Server Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 2: Create a new database at a remote server" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the 197.126.80.22 server ... Done!\n", + "\n", + "Creating a database named MY_DB at the 197.126.80.22 server. Please wait.\n", + "\n", + "The database \"MY_DB\" has been created!\n", + "\n", + "Disconnecting from the 197.126.80.22 server ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-createdb_REMOTE.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.createdb() API to #\n", + "# create a database on a remote Db2 server. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.conn_errormsg() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "hostName = \"197.126.80.22\" # IP Address Of A Remote Server\n", + "portNum = \"50000\" # Port Number Used By Db2\n", + "userID = \"db2inst2\" # User ID (Recognized By The Remote Server)\n", + "passWord = \"ibmdb2\" # User Password\n", + "svrConnection = None\n", + "dbName = \"MY_DB\"\n", + "returnCode = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server\n", + "conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " svrConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Create A New Database At The Remote Server\n", + "print(\"Creating a database named \" + dbName + \" at the \" + hostName + \" server. Please wait.\")\n", + "try:\n", + " returnCode = ibm_db.createdb(svrConnection, dbName)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Database Could Not Be Created, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"ERROR: Unable to create the \" + dbName + \" database.\\n\")\n", + " errorMsg = ibm_db.conn_errormsg(svrConnection)\n", + " print(errorMsg + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Display A Status Message Indicating The Database Was Created And Close The\n", + "# Db2 Server Connection That Was Opened Earlier\n", + "else:\n", + " print(\"\\nThe database \\\"\" + dbName + \"\\\" has been created!\\n\")\n", + " conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-createdbNX.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-createdbNX.ipynb new file mode 100644 index 0000000..db9e020 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-createdbNX.ipynb @@ -0,0 +1,414 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.createdbNX()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Create a new database using the name and code set specified; if the datebase already exists, do not return an error." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.createdbNX ( IBM_DBConnection `*`connection`*`, string `*`dbName`*` [, string `*`codeSet`*` ] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server connection. \n", + "* __*dbName*__         : The name to assign to the database that is to be created. \n", + "* __*codeSet*__         : The code set that is to be used for storing data that is entered into the database. If a __*codeSet*__ value is not specified, the UTF-8 (Unicode) code set is used." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : The database specified already exists or was successfully created. \n", + "* `False`    : The database specified could not be created." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.createdbNX()__ API is used to create a new database and assign it the name specified; the code set that is to be used for storing data entered into the database can also be specified when this API is executed. (The *code set* controls how unique numbers are assigned to characters in a particular character set.)

\n", + " \n", + "It's important to note that when this API is used, the name that is to be assigned to the database being created *should* be unique from all other database names in the system database or local database directory. If the name provided is the same as that of a database that already exists, the database will not be created; however, an error will __not__ be produced. *This is different from when the __ibm_db.createdb()__ API is used to create a database and the name specified matches the name of a database that already exists.*" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Examples:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 1: Create a new database at a local server" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the local server ... Done!\n", + "\n", + "Creating a database named MY_DB at the local server. Please wait.\n", + "\n", + "The database \"MY_DB\" has been created!\n", + "\n", + "Disconnecting from the local server ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-createdbNX_LOCAL.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.createdbNX() API #\n", + "# to create a local Db2 database. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.conn_errormsg() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "userID = \"db2inst1\" # User ID (Recognized By The Local Server)\n", + "passWord = \"Passw0rd\" # User Password\n", + "svrConnection = None\n", + "dbName = \"MY_DB\"\n", + "returnCode = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To The Local Db2 Server\n", + "conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " svrConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Create A New Database At The Local Server\n", + "print(\"Creating a database named \" + dbName + \" at the local server. Please wait.\")\n", + "try:\n", + " returnCode = ibm_db.createdbNX(svrConnection, dbName)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Database Could Not Be Created, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"ERROR: Unable to create the \" + dbName + \" database.\\n\")\n", + " errorMsg = ibm_db.conn_errormsg(svrConnection)\n", + " print(errorMsg + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + " \n", + "# Otherwise, Display A Status Message \n", + "else:\n", + " print(\"\\nThe database \\\"\" + dbName + \"\\\" has been created!\\n\")\n", + "\n", + "# Close The Db2 Server Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 2: Create a new database at a remote server" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the 197.126.80.22 server ... Done!\n", + "\n", + "Creating a database named MY_DB at the 197.126.80.22 server. Please wait.\n", + "\n", + "The database \"MY_DB\" has been created!\n", + "\n", + "Disconnecting from the 197.126.80.22 server ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-createdbNX_REMOTE.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.createdbNX() API #\n", + "# to create a database on a remote Db2 server. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.conn_errormsg() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "hostName = \"197.126.80.22\" # IP Address Of A Remote Server\n", + "portNum = \"50000\" # Port Number Used By Db2\n", + "userID = \"db2inst2\" # User ID (Recognized By The Remote Server)\n", + "passWord = \"ibmdb2\" # User Password\n", + "svrConnection = None\n", + "dbName = \"MY_DB\"\n", + "returnCode = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server\n", + "conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " svrConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Create A New Database At The Remote Server\n", + "print(\"Creating a database named \" + dbName + \" at the \" + hostName + \" server. Please wait.\")\n", + "try:\n", + " returnCode = ibm_db.createdbNX(svrConnection, dbName)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Database Could Not Be Created, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"ERROR: Unable to create the \" + dbName + \" database.\\n\")\n", + " errorMsg = ibm_db.conn_errormsg(svrConnection)\n", + " print(errorMsg + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Display A Status Message Indicating The Database Was Created And Close The\n", + "# Db2 Server Connection That Was Opened Earlier\n", + "else:\n", + " print(\"\\nThe database \\\"\" + dbName + \"\\\" has been created!\\n\")\n", + " conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-cursor_type.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-cursor_type.ipynb new file mode 100644 index 0000000..02d3ff5 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-cursor_type.ipynb @@ -0,0 +1,379 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.cursor_type()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve information about the type of cursor currently being used." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`int ibm_db.cursor_type( IBM_DBStatement `*`statement`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return Values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, one of the following values:

\n", + " \n", + " * `0` or `ibm_db.SQL_CURSOR_FORWARD_ONLY`          : A forward only cursor is being used.\n", + " * `1` or `ibm_db. SQL_CURSOR_KEYSET_DRIVEN`      : A keyset-driven cursor is being used.\n", + " * `2` or `ibm_db.SQL_CURSOR_DYNAMIC`                    : A dynamic, scrollable cursor is being used. Dynamic cursors are only supported by Db2 for z/OS servers. \n", + " * `3` or `ibm_db.SQL_CURSOR_STATIC`                      : A static cursor is being used.\n", + "\n", + " \n", + "\n", + "\n", + "* If __unsuccessful__, a Python interpreter error." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.cursor_type()__ API is used to retrieve information about the type of cursor currently being used. This API can be used in place of the __ibm_db.get_option()__ API to determine if you are working with a forward-only cursor or a scrollable cursor.\n", + "\n", + "It's important to note that if a cursor type that is not supported was specified with the __ibm_db.prepare()__, __ibm_db.exec_immediate()__, or __ibm_db.set_option()__ API, that cursor type is substituteed with a different cursor type; for a mixed or dynamic cursor, __ibm_db__ substitutes, in order, a keyset-driven cursor or a static cursor. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Setting cursor type to SQL_CURSOR_FORWARD_ONLY\n", + "\n", + "Executing the SQL statement \"SELECT * FROM department\" ... Done!\n", + "\n", + "Obtaining information about the type of cursor being used ... Done!\n", + "\n", + "Type of cursor being used: Forward only (SQL_CURSOR_FORWARD_ONLY)\n", + "\n", + "\n", + "Setting cursor type to SQL_CURSOR_KEYSET_DRIVEN\n", + "\n", + "Executing the SQL statement \"SELECT * FROM department\" ... Done!\n", + "\n", + "Obtaining information about the type of cursor being used ... Done!\n", + "\n", + "Type of cursor being used: Keyset driven (SQL_CURSOR_KEYSET_DRIVEN)\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-cursor_type.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.cursor_type() API #\n", + "# to determine the type of cursor being used. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.set_option() #\n", + "# ibm_db.exec_immediate() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "cursorType = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT * FROM department\"\n", + "\n", + "# Create A Dictionary That Contains The Value Needed To Specify That A Forward Only Cursor\n", + "# Should Be Used\n", + "print(\"Setting cursor type to SQL_CURSOR_FORWARD_ONLY\\n\")\n", + "stmtOption = {ibm_db.SQL_ATTR_CURSOR_TYPE: ibm_db.SQL_CURSOR_FORWARD_ONLY}\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement, stmtOption)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified\n", + "print(\"Obtaining information about the type of cursor being used ... \", end=\"\")\n", + "try:\n", + " cursorType = ibm_db.cursor_type(resultSet)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If Information About The Cursor Could Not Be Obtained, Display An Error Message And Exit \n", + "if cursorType is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified\n", + "print(\"Type of cursor being used: \", end=\"\")\n", + "\n", + "if cursorType == ibm_db.SQL_CURSOR_FORWARD_ONLY:\n", + " print(\"Forward only (SQL_CURSOR_FORWARD_ONLY)\\n\")\n", + "elif cursorType == ibm_db.SQL_CURSOR_KEYSET_DRIVEN:\n", + " print(\"Keyset driven (SQL_CURSOR_KEYSET_DRIVEN)\\n\")\n", + "elif cursorType == ibm_db.SQL_CURSOR_DYNAMIC:\n", + " print(\"Dynamic (SQL_CURSOR_DYNAMIC)\\n\")\n", + "elif cursorType == ibm_db.SQL_CURSOR_STATIC:\n", + " print(\"Static (SQL_CURSOR_STATIC)\\n\")\n", + "else:\n", + " print(\"Unknown\\n\")\n", + "\n", + "# Create A Dictionary That Contains The Value Needed To Specify That A Keyset-Driven Cursor\n", + "# Should Be Used\n", + "print(\"\\nSetting cursor type to SQL_CURSOR_KEYSET_DRIVEN\\n\")\n", + "stmtOption = {ibm_db.SQL_ATTR_CURSOR_TYPE: ibm_db.SQL_CURSOR_KEYSET_DRIVEN}\n", + "\n", + "# Execute The SQL Statement Defined Earlier\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement, stmtOption)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified\n", + "print(\"Obtaining information about the type of cursor being used ... \", end=\"\")\n", + "try:\n", + " cursorType = ibm_db.cursor_type(resultSet)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If Information About The Cursor Could Not Be Obtained, Display An Error Message And Exit \n", + "if cursorType is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified\n", + "print(\"Type of cursor being used: \", end=\"\")\n", + "\n", + "if cursorType == ibm_db.SQL_CURSOR_FORWARD_ONLY:\n", + " print(\"Forward only (SQL_CURSOR_FORWARD_ONLY)\\n\")\n", + "elif cursorType == ibm_db.SQL_CURSOR_KEYSET_DRIVEN:\n", + " print(\"Keyset driven (SQL_CURSOR_KEYSET_DRIVEN)\\n\")\n", + "elif cursorType == ibm_db.SQL_CURSOR_DYNAMIC:\n", + " print(\"Dynamic (SQL_CURSOR_DYNAMIC)\\n\")\n", + "elif cursorType == ibm_db.SQL_CURSOR_STATIC:\n", + " print(\"Static (SQL_CURSOR_STATIC)\\n\")\n", + "else:\n", + " print(\"Unknown\\n\")\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-dropdb.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-dropdb.ipynb new file mode 100644 index 0000000..3c44cd6 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-dropdb.ipynb @@ -0,0 +1,412 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.dropdb()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Delete (drop) the database specified." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.dropdb( IBM_DBConnection `*`connection,`*` string `*`dbName`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server connection. \n", + "* __*dbName*__         : The name of the database that is to be deleted (dropped)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : The database specified was deleted (dropped). \n", + "* `False`    : The database specified could not be deleted (dropped)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.dropdb()__ API is used to delete (drop) an existing database and remove information about it from both the system database directory and the local database directory." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Examples:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 1: Delete a database stored on a local server" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the local server ... Done!\n", + "\n", + "Dropping a database named MY_DB at the local server. Please wait.\n", + "\n", + "The database \"MY_DB\" has been deleted!\n", + "\n", + "Disconnecting from the local server ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-dropdb_LOCAL.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.dropdb() API to #\n", + "# delete (drop) a local Db2 database. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.conn_errormsg() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "userID = \"db2inst1\" # User ID (Recognized By The Local Server)\n", + "passWord = \"Passw0rd\" # User Password\n", + "svrConnection = None\n", + "dbName = \"MY_DB\"\n", + "returnCode = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Remote Db2 Server\n", + "conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " svrConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Delete (Drop) A Database At The Remote Server\n", + "print(\"Dropping a database named \" + dbName + \" at the local server. Please wait.\")\n", + "try:\n", + " returnCode = ibm_db.dropdb(svrConnection, dbName)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Database Could Not Be Deleted, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"ERROR: Unable to drop the \" + dbName + \" database.\\n\")\n", + " errorMsg = ibm_db.conn_errormsg(svrConnection)\n", + " print(errorMsg + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Display A Status Message And Verify That Information About The Database\n", + "# That Was Just Deleted No Longer Exists In The Db2 System Database Directory\n", + "else:\n", + " print(\"\\nThe database \\\"\" + dbName + \"\\\" has been deleted!\\n\")\n", + "\n", + "# Close The Db2 Server Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 2: Delete a database stored on a remote server" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the 197.126.80.22 server ... Done!\n", + "\n", + "Dropping a database named MY_DB at the 197.126.80.22 server. Please wait.\n", + "\n", + "The database \"MY_DB\" has been deleted!\n", + "\n", + "Disconnecting from the 197.126.80.22 server ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-dropdb_REMOTE.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.dropdb() API to #\n", + "# delete (drop) a database stored on a remote Db2 server. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.conn_errormsg() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "hostName = \"197.126.80.22\" # IP Address Of A Remote Server\n", + "portNum = \"50000\" # Port Number Used By Db2\n", + "userID = \"db2inst2\" # User ID (Recognized By The Remote Server)\n", + "passWord = \"ibmdb2\" # User Password\n", + "svrConnection = None\n", + "dbName = \"MY_DB\"\n", + "returnCode = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Remote Db2 Server\n", + "conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " svrConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Delete (Drop) A Database At The Remote Server\n", + "print(\"Dropping a database named \" + dbName + \" at the \" + hostName + \" server. Please wait.\")\n", + "try:\n", + " returnCode = ibm_db.dropdb(svrConnection, dbName)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Database Could Not Be Deleted, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"ERROR: Unable to drop the \" + dbName + \" database.\\n\")\n", + " errorMsg = ibm_db.conn_errormsg(svrConnection)\n", + " print(errorMsg + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Display A Status Message That States The Database Was Deleted And Close The\n", + "# Db2 Server Connection That Was Opened Earlier\n", + "else:\n", + " print(\"\\nThe database \\\"\" + dbName + \"\\\" has been deleted!\\n\")\n", + " conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-exec_immediate.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-exec_immediate.ipynb new file mode 100644 index 0000000..67cea32 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-exec_immediate.ipynb @@ -0,0 +1,313 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.exec_immediate()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Prepare and execute an SQL statement, using values supplied for parameter markers that were coded in the statement
(if any)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`IBM_DBStatement ibm_db.exec_immediate( IBM_DBConnection `*`connection,`*` string `*`statement`*` [, dictionary `*`options`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__        : A valid Db2 server or database connection.\n", + "* __*SQLstatement*__   : A valid, executable SQL statement (that may or may not contain one or more parameter markers).\n", + "* __options__              : A dictionary containing key-value pairs for the statement attributes that are to be set when the statement provided in the __*SQLstatement*__ parameter is prepared. Valid keys and values are:

\n", + " \n", + " * `ibm_db.SQL_ATTR_CURSOR_TYPE`                             : Specifies the type of cursor that is to be used for processing result sets. Valid values are:\n", + " * `ibm_db.SQL_CURSOR_FORWARD_ONLY`                 : A forward only cursor should be used (i.e., a cursor that only scrolls forward).\n", + " * `ibm_db. SQL_CURSOR_KEYSET_DRIVEN`             : A keyset-driven cursor should be used.\n", + " * `ibm_db.SQL_CURSOR_STATIC`                             : A static cursor should be used.\n", + " * `ibm_db.SQL_CURSOR_DYNAMIC`                           : A dynamic, scrollable cursor that detects all changes to the result set, should be used. Dynamic cursors are only supported by Db2 for z/OS servers.\n", + " * `ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH`                 : Enables Db2 to determine the number of rows that are returned by a query (so the entire result set can be prefetched into memory, when possible); `ibm_db.SQL_ROWCOUNT_PREFETCH_ON` will turn this behavior __ON__ and `ibm_db.SQL_ROWCOUNT_PREFETCH_OFF` will turn it __OFF__.\n", + " * `ibm_db.SQL_ATTR_QUERY_TIMEOUT`                         : The number of seconds to wait for an SQL statement to execute before aborting and returning to the application. This option can be used to terminate long running queries — the default value of __0__ means an application will wait indefinitely for the server to complete execution." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, a valid `IBM_DBStatement` object (that contains a result set if the SQL statement specified in the __*SQLstatement*__ parameter was a __SELECT__ statement).\n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.exec_immediate()__ API is used to prepare and execute an SQL statement, using values supplied for parameter markers that were coded in the statement (if there are any).

\n", + " \n", + "If you plan to execute the same SQL statement repeatedly (with or without parameter marker values), consider using the __ibm_db.prepare()__ and __ibm_db.execute()__ APIs instead. Refer to the notebook for __ibm_db.prepare()__ (i.e., the file *ibm_db-prepare.ipynb*) for a brief discussion of the advantages of using __ibm_db.prepare()__ and __ibm_db.execute()__, as opposed to __ibm_db.exec_immediate()__ to perform SQL operations against a Db2 database.

\n", + " \n", + "If the SQL statement executed returns a result set, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row.

\n", + "\n", + "It is important to note that if you interject Python variables into the SQL statement used with this API, you run the risk of creating an application that is vunerable to SQL injection attacks . Consequently, if you want to execute SQL statements that contain parameter markers, it is recommended that you use the __ibm_db.prepare()__ and __ibm_db.execute()__ APIs to avoid creating a potential security exposure.

" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT projno, projname FROM project WHERE prstaff < 2\" ... Done!\n", + "\n", + "Query results:\n", + "\n", + "PROJNO PROJNAME\n", + "______ _____________________\n", + "AD3112 PERSONNEL PROGRAMMING \n", + "IF2000 USER EDUCATION \n", + "OP2011 SCP SYSTEMS SUPPORT \n", + "OP2012 APPLICATIONS SUPPORT \n", + "OP2013 DB/DC SUPPORT \n", + "PL2100 WELD LINE PLANNING \n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-exec_immediate.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.exec_immediate() #\n", + "# API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.fetch_row() #\n", + "# ibm_db.result() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT projno, projname FROM project WHERE prstaff < 2\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Query results:\\n\")\n", + "print(\"PROJNO PROJNAME\")\n", + "print(\"______ _____________________\")\n", + "\n", + "# As Long As There Are Records In The Result Set Produced, ...\n", + "while (ibm_db.fetch_row(resultSet) is True):\n", + "\n", + " # Extract The Data Value For Each Column From The Current Record\n", + " projectNum = ibm_db.result(resultSet, 0)\n", + " projectName = ibm_db.result(resultSet, 1)\n", + "\n", + " # Format And Display The Data Retrieved\n", + " print(\"{:6} {:24}\" .format(projectNum, projectName))\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-execute.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-execute.ipynb new file mode 100644 index 0000000..a407012 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-execute.ipynb @@ -0,0 +1,331 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.execute()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Execute an SQL statement that has been prepared by the __ibm_db.prepare()__ API." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false + }, + "source": [ + "`bool ibm_db.execute( IBM_DBStatement `*`preparedStmt`*` [, tuple `*`paramValues`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*preparedStmt*__    : A prepared SQL statement returned from the __ibm_db.prepare()__ API. \n", + "* __*paramValues*__     : A tuple that contains values for each parameter marker used in the prepared SQL statement specified in the __*preparedStmt*__ parameter." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : The prepared SQL statement specified in the __*preparedStmt*__ parameter executed successfully. \n", + "* `False`    : The prepared SQL statement specified in the __*preparedStmt*__ parameter could not be executed." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.execute()__ API is used to execute an SQL statement that has been prepared by the __ibm_db.prepare()__ API. If the SQL statement returns a result set, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row.

\n", + " \n", + "Refer to the notebook for __ibm_db.prepare()__ (i.e., the file *ibm_db-prepare.ipynb*) for a brief discussion of the advantages of using __ibm_db.prepare()__ and __ibm_db.execute()__, as opposed to __ibm_db.exec_immediate()__ to perform SQL operations against a Db2 database." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Preparing the SQL statement \"SELECT projno, projname FROM project WHERE prstaff < 2\" ... Done!\n", + "\n", + "Executing the prepared SQL statement ... Done!\n", + "\n", + "Query results:\n", + "\n", + "PROJNO PROJNAME\n", + "______ _____________________\n", + "AD3112 PERSONNEL PROGRAMMING \n", + "IF2000 USER EDUCATION \n", + "OP2011 SCP SYSTEMS SUPPORT \n", + "OP2012 APPLICATIONS SUPPORT \n", + "OP2013 DB/DC SUPPORT \n", + "PL2100 WELD LINE PLANNING \n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-execute.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.execute() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.prepare() #\n", + "# ibm_db.fetch_tuple() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "preparedStmt = False\n", + "returnCode = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT projno, projname FROM project WHERE prstaff < 2\"\n", + "\n", + "# Prepare The SQL Statement Just Defined\n", + "print(\"Preparing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit\n", + "if preparedStmt is False:\n", + " print(\"\\nERROR: Unable to prepare the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Execute The SQL Statement Just Prepared\n", + "print(\"Executing the prepared SQL statement ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.execute(preparedStmt)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Query results:\\n\")\n", + "print(\"PROJNO PROJNAME\")\n", + "print(\"______ _____________________\")\n", + "\n", + "# As Long As There Are Records In The Result Set Produced, ...\n", + "noData = False\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Tuple\n", + " try:\n", + " dataRecord = ibm_db.fetch_tuple(preparedStmt)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Data Retrieved\n", + " else:\n", + " print(\"{:<6} {:24}\" .format(dataRecord[0], dataRecord[1])) \n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-execute_many.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-execute_many.ipynb new file mode 100644 index 0000000..bcd6834 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-execute_many.ipynb @@ -0,0 +1,322 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.execute_many()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Execute an SQL statement that has been prepared by the __ibm_db.prepare()__ API, using the parameter sequences or mappings specified." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`mixed ibm_db.execute_many( IBM_DBStatement `*`preparedStmt,`*` tuple `*`seqOfParamValues`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*preparedStmt*__             : A prepared SQL statement returned from the __ibm_db.prepare()__ API.\n", + "* __*seqOfParamValues*__    : A tuple of tuples that contain values for each parameter marker used in the prepared SQL statement (that was speficied in the __*preparedStmt*__ parameter). " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an integer representing the number of rows that were inserted, updated, or deleted by the SQL statement specified in the __*preparedStmt*__ parameter.\n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.execute_many()__ API is used to execute an SQL statement that has been prepared by the __ibm_db.prepare()__ API, using a set of parameter sequences or mappings. Essentially, this API is used to perform bulk __INSERT__, __UPDATE__, and __DELETE__ operations. (To achieve optimum performance, this API utilizes *array input chaining* to minimize the number of round trips that have to be made between the client and the server.)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Number of records found in the DEPARTMENT table: 14\n", + "\n", + "Preparing the SQL statement \"INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)\" ... Done!\n", + "\n", + "Executing the prepared SQL statement ... Done!\n", + "\n", + "Number of records added : 3\n", + "\n", + "Number of records found in the DEPARTMENT table: 17\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-execute_many.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.execute_many() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.prepare() #\n", + "# ibm_db.fetch_tuple() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The get_row_count() Function That Has Been Defined In The File Named #\n", + "# \"ibm_db_tools.py\"; This Function Contains The Programming Logic Needed To Obtain And #\n", + "# Display The Number Of Rows (Records) Found In A Db2 Database Table. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import get_row_count\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "returnCode = None\n", + "preparedStmt = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table\n", + "returnCode = get_row_count(dbConnection, 'DEPARTMENT')\n", + "if returnCode is False:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The INSERT Statement (With Parameter Markers) That Is To Be Used To Add Data\n", + "# To The DEPARTMENT Table\n", + "sqlStatement = \"INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)\"\n", + "\n", + "# Prepare The SQL Statement Just Defined\n", + "print(\"Preparing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit\n", + "if preparedStmt is False:\n", + " print(\"\\nERROR: Unable to prepare the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Create A List Of Data Values That Are To Be Supplied For The Parameter Markers Coded\n", + "# In The INSERT Statement Specified\n", + "pmValues = (('K22', 'SALES', '000110'), \n", + " ('L22', 'FINANCE', '000120'), \n", + " ('M22', 'HUMAN RESOURCES', '000130'))\n", + "\n", + "# Execute The SQL Statement Just Prepared\n", + "print(\"Executing the prepared SQL statement ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.execute_many(preparedStmt, pmValues)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if returnCode is True:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message And Display The Number Of Records Added\n", + "else:\n", + " print(\"Done!\\n\")\n", + " print(\"Number of records added : {}\\n\" .format(returnCode))\n", + "\n", + " # Display The Number Of Rows That Exist In The DEPARTMENT Table Now\n", + " # (The Number Returned Should Reflect That Three Rows Were Added)\n", + " returnCode = get_row_count(dbConnection, 'DEPARTMENT')\n", + "\n", + " # Close The Database Connection That Was Opened Earlier\n", + " conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-fetch_assoc.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-fetch_assoc.ipynb new file mode 100644 index 0000000..079029e --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-fetch_assoc.ipynb @@ -0,0 +1,323 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.fetch_assoc()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve a row from a result set and copy its data to a dictionary." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`dictionary ibm_db.fetch_assoc( IBM_DBStatement `*`statement`*` [, int `*`rowNumber`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__        : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __rowNumber__     : A specific, one-indexed, row in the result set that data is to be retrieved from. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*rowNumber*__ value is provided:\n", + "* If __successful__, a dictionary containing values for every column in the result set, *for the row specified*.\n", + "* If __unsuccessful__ or if the row specified doesn't exist, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*rowNumber*__ value is not provided: \n", + "* If __successful__, a dictionary containing values for every column in the result set, *for the next row*.\n", + "* If __unsuccessful__ or if there are no rows left in the result set, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.fetch_assoc()__ API is used to retrieve a row (record) from a result set and copy its data to a dictionary. Depending on how it is called, it can advance a cursor to the next row in a result set and copy the data for that row into a dictionary. Or, it can be used to retrieve the data for a specific row — provided a keyset-driven, dynamic, or static cursor is used to traverse the result set. (*A warning will be issued if a specific row is requested and a forward-only cursor is used*.)

\n", + " \n", + "In either case, the value for the first column in the row will be stored in the first key-value pair of the dictionary — the key will be the name of the column; the value will be the data for that column in the row. The second column will be stored in the second key-value pair, and so on." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT deptname FROM department WHERE admrdept = 'A00'\" ... Done!\n", + "\n", + "Query results:\n", + "\n", + "DEPTNAME\n", + "____________________________\n", + "SPIFFY COMPUTER SERVICE DIV.\n", + "PLANNING \n", + "INFORMATION CENTER \n", + "DEVELOPMENT CENTER \n", + "SUPPORT SERVICES \n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-fetch_assoc.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.fetch_assoc() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT deptname FROM department WHERE admrdept = 'A00'\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Query results:\\n\")\n", + "print(\"DEPTNAME\")\n", + "print(\"____________________________\")\n", + "\n", + "# As Long As There Are Records In The Result Set Produced, ...\n", + "noData = False\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Data Retrieved\n", + " else:\n", + " print(\"{:20}\" .format(dataRecord['DEPTNAME']))\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-fetch_both.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-fetch_both.ipynb new file mode 100644 index 0000000..3606843 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-fetch_both.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.fetch_both()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve a row from a result set and copy its data to both a tuple *and* a dictionary." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`tuple/dictionary ibm_db.fetch_both( IBM_DBStatement `*`statement`*` [, int `*`rowNumber`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__        : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __rowNumber__     : A specific, one-indexed, row in the result set that data is to be retrieved from. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*rowNumber*__ value is provided:\n", + "* If __successful__, a tuple *and* a dictionary containing values for every column in the result set, *for the row specified*.\n", + "* If __unsuccessful__ or if the row specified doesn't exist, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*rowNumber*__ value is not provided: \n", + "* If __successful__, a tuple *and* dictionary containing values for every column in the result set, *for the next row*.\n", + "* If __unsuccessful__ or if there are no rows left in the result set, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.fetch_both()__ API is used to retrieve a row (record) from a result set and copy its data to both a tuple *and* a dictionary. Depending on how it is called, it can advance a cursor to the next row in a result set and copy the data for that row into a tuple and dictionary. Or, it can be used to retrieve the data for a specific row — provided a keyset-driven, dynamic, or static cursor is used to traverse the result set. (*A warning will be issued if a specific row is requested and a forward-only cursor is used*.)

\n", + " \n", + "In either case, the value for the first column in the row will be stored in the first position of the tuple returned (index position **0** ) *and* the first key-value pair of the dictionary returned, the second column will be stored in the second position/key-value pair, and so on." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT deptno, deptname FROM department WHERE admrdept = 'A00'\" ... Done!\n", + "\n", + "Query results:\n", + "\n", + "DEPTNO DEPTNAME\n", + "______ ______________________\n", + "A00 SPIFFY COMPUTER SERVICE DIV.\n", + "B01 PLANNING \n", + "C01 INFORMATION CENTER \n", + "D01 DEVELOPMENT CENTER \n", + "E01 SUPPORT SERVICES \n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-fetch_both.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.fetch_both() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT deptno, deptname FROM department WHERE admrdept = 'A00'\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Query results:\\n\")\n", + "print(\"DEPTNO DEPTNAME\")\n", + "print(\"______ ______________________\")\n", + "\n", + "# As Long As There Are Records In The Result Set Produced, ...\n", + "noData = False\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary And A Python Tuple\n", + " try:\n", + " dataRecord = ibm_db.fetch_both(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Data Retrieved\n", + " else:\n", + " print(\"{:6} \".format(dataRecord[0]), end=\"\") # Tuple Value\n", + " print(\"{:20}\" .format(dataRecord['DEPTNAME'])) # Dictionary Value\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-fetch_row.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-fetch_row.ipynb new file mode 100644 index 0000000..e3153ce --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-fetch_row.ipynb @@ -0,0 +1,318 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.fetch_row()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Move a cursor to a specific row in a result set, or advance a cursor to the next row in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.fetch_row( IBM_DBStatement `*`statement`*` [, int `*`rowNumber`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__        : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __rowNumber__     : A specific, one-indexed, row in the result set that data is to be retrieved from. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*rowNumber*__ value is provided:\n", + "* `True`      : The row specified exists in the result set. \n", + "* `False`    : The row specified does not exist in the result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*rowNumber*__ value is not provided: \n", + "* `True`      : A row exists in the result set. \n", + "* `False`    : There are no rows left in the result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.fetch_row()__ API is used to advance a cursor to the next row *or* move a cursor to a specific row in a result set. (*A keyset-driven, dynamic, or static cursor must be used when moving a cursor to a specific row — a warning will be issued if a specific row is requested and a forward-only cursor is used*.) Once a cursor has been moved to the appropriate row, the __ibm_db.result()__ API can be used to retrieve data for individual columns in that row.

\n", + " \n", + "As an alternative to using the __ibm_db.fetch_row()__ and __ibm_db.result()__ APIs to iterate through a result set and retrieve data values for individual columns, applications can use the __ibm_db.fetch_tuple()__, __ibm_db.fetch_assoc()__, or __ibm_db.fetch_both()__ API to position the cursor in a result set and retrieve the data for a complete row, in a single operation. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT deptname FROM department WHERE admrdept = 'A00'\" ... Done!\n", + "\n", + "Query results:\n", + "\n", + "DEPTNAME\n", + "____________________________\n", + "SPIFFY COMPUTER SERVICE DIV.\n", + "PLANNING\n", + "INFORMATION CENTER\n", + "DEVELOPMENT CENTER\n", + "SUPPORT SERVICES\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-fetch_row.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.fetch_row() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.result() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "dataValue = None\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT deptname FROM department WHERE admrdept = 'A00'\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Query results:\\n\")\n", + "print(\"DEPTNAME\")\n", + "print(\"____________________________\")\n", + "\n", + "# As Long As There Are Records In The Result Set Produced, ...\n", + "while (ibm_db.fetch_row(resultSet) is True):\n", + "\n", + " # Retrieve The Data From The Current Row\n", + " try:\n", + " dataValue = ibm_db.result(resultSet, 0)\n", + " except Exception:\n", + " pass\n", + "\n", + " # Display The Data Retrieved\n", + " if not dataValue is None:\n", + " print(dataValue)\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-fetch_tuple.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-fetch_tuple.ipynb new file mode 100644 index 0000000..c22b46a --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-fetch_tuple.ipynb @@ -0,0 +1,323 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.fetch_tuple()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve a row from a result set and copy its data to a tuple." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`tuple ibm_db.fetch_tuple( IBM_DBStatement `*`statement`*` [, int `*`rowNumber`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__        : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __rowNumber__     : A specific, one-indexed, row in the result set that data is to be retrieved from. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*rowNumber*__ value is provided:\n", + "* If __successful__, a tuple containing values for every column in the result set, *for the row specified*.\n", + "* If __unsuccessful__ or if the row specified doesn't exist, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*rowNumber*__ value is not provided: \n", + "* If __successful__, a tuple containing values for every column in the result set, *for the next row*.\n", + "* If __unsuccessful__ or if there are no rows left in the result set, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.fetch_tuple()__ API is used to retrieve a row (record) from a result set and copy its data to a tuple. Depending on how it is called, it can advance a cursor to the next row in a result set and copy the data for that row into a tuple. Or, it can be used to retrieve the data for a specific row — provided a keyset driven, dynamic, or static cursor is used to traverse the result set. (*A warning will be issued if a specific row is requested and a forward-only cursor is used*.)

\n", + " \n", + "In either case, the value for the first column in the row will be stored in the first position of the tuple (index position **0** ), the second column will be stored in the second position (index position __1__ ) and so on." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT deptname FROM department WHERE admrdept = 'A00'\" ... Done!\n", + "\n", + "Query results:\n", + "\n", + "DEPTNAME\n", + "____________________________\n", + "SPIFFY COMPUTER SERVICE DIV.\n", + "PLANNING\n", + "INFORMATION CENTER\n", + "DEVELOPMENT CENTER\n", + "SUPPORT SERVICES\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-fetch_tuple.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.fetch_tuple() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT deptname FROM department WHERE admrdept = 'A00'\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Query results:\\n\")\n", + "print(\"DEPTNAME\")\n", + "print(\"____________________________\")\n", + "\n", + "# As Long As There Are Records In The Result Set Produced, ...\n", + "noData = False\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Tuple\n", + " try:\n", + " dataRecord = ibm_db.fetch_tuple(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Data Retrieved\n", + " else:\n", + " print(dataRecord[0]) \n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-field_display_size.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-field_display_size.ipynb new file mode 100644 index 0000000..b9cd8de --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-field_display_size.ipynb @@ -0,0 +1,334 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.field_display_size()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Determine the maximum number of bytes needed to display a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`int ibm_db.field_display_size( IBM_DBStatement `*`statement,`*` mixed `*`column`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __column__        : The zero-indexed position of the column *or* the name of the column in the result set that display size information is to be obtained for. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return Values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an integer containing the maximum number of bytes required to display the column specified.\n", + "* If __unsuccessful__ or if the column doesn't exist, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.field_display_size()__ API is used to determine the maximum number of bytes needed to display the information stored in a column of a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT * FROM employee\" ... Done!\n", + "\n", + "Examining the columns returned in the result set produced ... Done!\n", + "\n", + "Result set information:\n", + "\n", + "COLUMN NAME DATA DISPLAY SIZE\n", + "___________ _________________\n", + "EMPNO 6\n", + "FIRSTNME 12\n", + "MIDINIT 1\n", + "LASTNAME 15\n", + "WORKDEPT 3\n", + "PHONENO 4\n", + "HIREDATE 10\n", + "JOB 8\n", + "EDLEVEL 6\n", + "SEX 1\n", + "BIRTHDATE 10\n", + "SALARY 11\n", + "BONUS 11\n", + "COMM 11\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-field_display_size.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_display_size() #\n", + "# API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.num_fields() #\n", + "# ibm_db.field_name() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "numColumns = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT * FROM employee\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed\n", + "print(\"Examining the columns returned in the result set produced ... \", end=\"\")\n", + "try:\n", + " numColumns = ibm_db.num_fields(resultSet)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error\n", + "# Message And Exit \n", + "if numColumns is False:\n", + " print(\"\\nERROR: Unable to obtain information about the result set produced.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Result set information:\\n\")\n", + "print(\"COLUMN NAME DATA DISPLAY SIZE\")\n", + "print(\"___________ _________________\")\n", + "\n", + "# As Long As There Is Column Information, ...\n", + "for loopCounter in range(0, numColumns):\n", + "\n", + " # Get The Name Of The Current Column\n", + " colName = ibm_db.field_name(resultSet, loopCounter)\n", + "\n", + " # Get The Display Size Of The Data For The Current Column\n", + " colDispSize = ibm_db.field_display_size(resultSet, loopCounter)\n", + "\n", + " # Format And Display The Data Retrieved\n", + " if (not colName is False) and (not colDispSize is False):\n", + " print(\"{:<13} {:>15}\" .format(colName, colDispSize))\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-field_name.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-field_name.ipynb new file mode 100644 index 0000000..7981b25 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-field_name.ipynb @@ -0,0 +1,330 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.field_name()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Determine the name of a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`string ibm_db.field_name( IBM_DBStatement `*`statement,`*` mixed `*`column`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __column__        : The zero-indexed position of the column *or* the name of the column in the result set that column name information is to be obtained for. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, a character string containing the name of the column specified.\n", + "* If __unsuccessful__ or if the column doesn't exist, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.field_name()__ API is used to determine the name of a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT * FROM employee\" ... Done!\n", + "\n", + "Examining the columns returned in the result set produced ... Done!\n", + "\n", + "Result set information:\n", + "\n", + "COLUMN NUMBER COLUMN NAME\n", + "_____________ ___________\n", + " 0 EMPNO \n", + " 1 FIRSTNME \n", + " 2 MIDINIT \n", + " 3 LASTNAME \n", + " 4 WORKDEPT \n", + " 5 PHONENO \n", + " 6 HIREDATE \n", + " 7 JOB \n", + " 8 EDLEVEL \n", + " 9 SEX \n", + " 10 BIRTHDATE \n", + " 11 SALARY \n", + " 12 BONUS \n", + " 13 COMM \n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-field_name.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_name() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.num_fields() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "numColumns = False\n", + "colName = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT * FROM employee\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed\n", + "print(\"Examining the columns returned in the result set produced ... \", end=\"\")\n", + "try:\n", + " numColumns = ibm_db.num_fields(resultSet)\n", + "except Exception:\n", + " pass\n", + " \n", + "# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error\n", + "# Message And Exit \n", + "if numColumns is False:\n", + " print(\"\\nERROR: Unable to obtain information about the result set produced.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + " \n", + "# Display A Report Header\n", + "print(\"Result set information:\\n\")\n", + "print(\"COLUMN NUMBER COLUMN NAME\")\n", + "print(\"_____________ ___________\")\n", + "\n", + "# As Long As There Is Column Information, ...\n", + "for loopCounter in range(0, numColumns):\n", + "\n", + " # Get The Name Of The Current Column\n", + " colName = ibm_db.field_name(resultSet, loopCounter)\n", + "\n", + " # Format And Display The Data Retrieved\n", + " if not colName is False:\n", + " print(\"{:>13} {:<11}\" .format(loopCounter, colName))\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-field_num.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-field_num.ipynb new file mode 100644 index 0000000..9faa724 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-field_num.ipynb @@ -0,0 +1,291 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.field_num()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Determine the position of a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`int ibm_db.field_num( IBM_DBStatement `*`statement,`*` mixed `*`column`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __column__        : The zero-indexed position of the column *or* the name of the column in the result set that position information is to be obtained for. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an integer containing the zero-indexed position of the column specified.\n", + "* If __unsuccessful__ or if the column doesn't exist, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.field_num()__ API is used to determine the ordinal position, starting from zero, of a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT * FROM employee\" ... Done!\n", + "\n", + "'BIRTHDATE' data can be found in column number 10 of the result set produced.\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-field_num.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_num() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "columnNumber = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT * FROM employee\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Find Out Which Column In The Result Set Produced By The Query Just Executed Contains Data \n", + "# That Was Retrieved From The \"BIRTHDATE\" Column Of The Table\n", + "try:\n", + " columnNumber = ibm_db.field_num(resultSet, 'BIRTHDATE')\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Column Number For The \"BIRTHDATE\" Column Could Not Be Obtained, Display An Error\n", + "# Message And Exit \n", + "if columnNumber is False:\n", + " print(\"\\nERROR: Unable to obtain information about the result set produced.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Format And Display The Data Retrieved\n", + "print(\"\\'BIRTHDATE\\' data can be found in column number {:<2} \" .format(columnNumber), end=\"\")\n", + "print(\"of the result set produced.\\n\")\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-field_precision.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-field_precision.ipynb new file mode 100644 index 0000000..38e75d3 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-field_precision.ipynb @@ -0,0 +1,322 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.field_precision()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Determine the precision of a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`int ibm_db.field_precision( IBM_DBStatement `*`statement,`*` mixed `*`column`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __column__        : The zero-indexed position of the column *or* the name of the column in the result set that precision information is to be obtained for. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an integer containing the precision of the column specified.\n", + "* If __unsuccessful__ or if the column doesn't exist, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.field_precision()__ API is used to determine the precision (i.e., total number of digits) of a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT salary, bonus, comm FROM employee\" ... Done!\n", + "\n", + "Examining the columns returned in the result set produced ... Done!\n", + "\n", + "Result set information:\n", + "\n", + "COLUMN NAME PRECISION (TOTAL NUMBER OF DIGITS)\n", + "___________ __________________________________\n", + "SALARY 9\n", + "BONUS 9\n", + "COMM 9\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-field_precision.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_precision() #\n", + "# API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.num_fields() #\n", + "# ibm_db.field_name() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "numColumns = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT salary, bonus, comm FROM employee\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed\n", + "print(\"Examining the columns returned in the result set produced ... \", end=\"\")\n", + "try:\n", + " numColumns = ibm_db.num_fields(resultSet)\n", + "except Exception:\n", + " pass\n", + " \n", + "# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error\n", + "# Message And Exit \n", + "if numColumns is False:\n", + " print(\"\\nERROR: Unable to obtain information about the result set produced.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Result set information:\\n\")\n", + "print(\"COLUMN NAME PRECISION (TOTAL NUMBER OF DIGITS)\")\n", + "print(\"___________ __________________________________\")\n", + "\n", + "# As Long As There Is Column Information, ...\n", + "for loopCounter in range(0, numColumns):\n", + "\n", + " # Get The Name Of The Current Column\n", + " colName = ibm_db.field_name(resultSet, loopCounter)\n", + "\n", + " # Get The Precision Of The Current Column\n", + " colPrecision = ibm_db.field_precision(resultSet, loopCounter)\n", + "\n", + " # Format And Display The Data Retrieved\n", + " if (not colName is False) and (not colPrecision is False):\n", + " print(\"{:<13} {:>32}\" .format(colName, colPrecision))\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-field_scale.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-field_scale.ipynb new file mode 100644 index 0000000..e88a483 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-field_scale.ipynb @@ -0,0 +1,322 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.field_scale()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Determine the scale of a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`int ibm_db.field_scale( IBM_DBStatement `*`statement,`*` mixed `*`column`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __column__        : The zero-indexed position of the column *or* the name of the column in the result set that scale information is to be obtained for. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an integer containing the scale of the column specified.\n", + "* If __unsuccessful__ or if the column doesn't exist, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.field_scale()__ API is used to determine the scale (i.e., number of decimal digits) of a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT salary, bonus, comm FROM employee\" ... Done!\n", + "\n", + "Examining the columns returned in the result set produced ... Done!\n", + "\n", + "Result set information:\n", + "\n", + "COLUMN NAME SCALE (DECIMAL DIGITS)\n", + "___________ ______________________\n", + "SALARY 2\n", + "BONUS 2\n", + "COMM 2\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-field_scale.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_scale() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.num_fields() #\n", + "# ibm_db.field_name() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "numColumns = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT salary, bonus, comm FROM employee\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed\n", + "print(\"Examining the columns returned in the result set produced ... \", end=\"\")\n", + "try:\n", + " numColumns = ibm_db.num_fields(resultSet)\n", + "except Exception:\n", + " pass\n", + " \n", + "# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error\n", + "# Message And Exit \n", + "if numColumns is False:\n", + " print(\"\\nERROR: Unable to obtain information about the result set produced.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Result set information:\\n\")\n", + "print(\"COLUMN NAME SCALE (DECIMAL DIGITS)\")\n", + "print(\"___________ ______________________\")\n", + "\n", + "# As Long As There Is Column Information, ...\n", + "for loopCounter in range(0, numColumns):\n", + "\n", + " # Get The Name Of The Current Column\n", + " colName = ibm_db.field_name(resultSet, loopCounter)\n", + "\n", + " # Get The Scale Of The Current Column\n", + " colScale = ibm_db.field_scale(resultSet, loopCounter)\n", + "\n", + " # Format And Display The Data Retrieved\n", + " if (not colName is False) and (not colScale is False):\n", + " print(\"{:<13} {:>20}\" .format(colName, colScale))\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-field_type.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-field_type.ipynb new file mode 100644 index 0000000..69daf08 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-field_type.ipynb @@ -0,0 +1,333 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.field_type()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Determine the data type of a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`string ibm_db.field_type( IBM_DBStatement `*`statement,`*` mixed `*`column`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __column__        : The zero-indexed position of the column *or* the name of the column in the result set that data type information is to be obtained for. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, a string containing the data type of the column specified.\n", + "* If __unsuccessful__ or if the column doesn't exist, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.field_type()__ API is used to obtain a string representation of the SQL data type of a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT * FROM employee\" ... Done!\n", + "\n", + "Examining the columns returned in the result set produced ... Done!\n", + "\n", + "Result set information:\n", + "\n", + "COLUMN NAME DATA TYPE\n", + "___________ _________\n", + "EMPNO STRING\n", + "FIRSTNME STRING\n", + "MIDINIT STRING\n", + "LASTNAME STRING\n", + "WORKDEPT STRING\n", + "PHONENO STRING\n", + "HIREDATE DATE\n", + "JOB STRING\n", + "EDLEVEL INT\n", + "SEX STRING\n", + "BIRTHDATE DATE\n", + "SALARY DECIMAL\n", + "BONUS DECIMAL\n", + "COMM DECIMAL\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-field_type.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_type() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.num_fields() #\n", + "# ibm_db.field_name() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "numColumns = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT * FROM employee\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed\n", + "print(\"Examining the columns returned in the result set produced ... \", end=\"\")\n", + "try:\n", + " numColumns = ibm_db.num_fields(resultSet)\n", + "except Exception:\n", + " pass\n", + " \n", + "# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error\n", + "# Message And Exit \n", + "if numColumns is False:\n", + " print(\"\\nERROR: Unable to obtain information about the result set produced.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Result set information:\\n\")\n", + "print(\"COLUMN NAME DATA TYPE\")\n", + "print(\"___________ _________\")\n", + "\n", + "# As Long As There Is Column Information, ...\n", + "for loopCounter in range(0, numColumns):\n", + "\n", + " # Get The Name Of The Current Column\n", + " colName = ibm_db.field_name(resultSet, loopCounter)\n", + "\n", + " # Get The Data Type Of The Current Column\n", + " colDataType = ibm_db.field_type(resultSet, loopCounter)\n", + "\n", + " # Format And Display The Data Retrieved - Show Data Types In Upper Case\n", + " if (not colName is False) and (not colDataType is False):\n", + " print(\"{:<13} {:>7}\" .format(colName, colDataType.upper()))\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-field_width.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-field_width.ipynb new file mode 100644 index 0000000..3b5f104 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-field_width.ipynb @@ -0,0 +1,322 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.field_width()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Determine the width (size) of a column in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`int ibm_db.field_width( IBM_DBStatement `*`statement,`*` mixed `*`column`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __column__        : The zero-indexed position of the column *or* the name of the column in the result set that width information is to be obtained for. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an integer containing the width of the column specified.\n", + "* If __unsuccessful__ or if the column doesn't exist, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.field_width()__ API is used to determine the width (size) of a column in a result set. That is, the maximum width of the column if it has a fixed-length data type and the actual width of the column if it has a variable-length data type." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT * FROM emp_resume\" ... Done!\n", + "\n", + "Examining the columns returned in the result set produced ... Done!\n", + "\n", + "Result set information:\n", + "\n", + "COLUMN NAME MAXIMUM VALUE SIZE (IN BYTES)\n", + "_____________ _____________________________\n", + "EMPNO 6\n", + "RESUME_FORMAT 10\n", + "RESUME 5120\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-field_width.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_width() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.num_fields() #\n", + "# ibm_db.field_name() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "numColumns = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT * FROM emp_resume\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed\n", + "print(\"Examining the columns returned in the result set produced ... \", end=\"\")\n", + "try:\n", + " numColumns = ibm_db.num_fields(resultSet)\n", + "except Exception:\n", + " pass\n", + " \n", + "# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error\n", + "# Message And Exit \n", + "if numColumns is False:\n", + " print(\"\\nERROR: Unable to obtain information about the result set produced.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Result set information:\\n\")\n", + "print(\"COLUMN NAME MAXIMUM VALUE SIZE (IN BYTES)\")\n", + "print(\"_____________ _____________________________\")\n", + "\n", + "# As Long As There Is Column Information, ...\n", + "for loopCounter in range(0, numColumns):\n", + "\n", + " # Get The Name Of The Current Column\n", + " colName = ibm_db.field_name(resultSet, loopCounter)\n", + "\n", + " # Get The Size Of The Data Allowed In The Current Column\n", + " colWidth = ibm_db.field_width(resultSet, loopCounter)\n", + "\n", + " # Format And Display The Data Retrieved\n", + " if (not colName is False) and (not colWidth is False):\n", + " print(\"{:<13} {:>29}\" .format(colName, colWidth))\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-foreign_keys.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-foreign_keys.ipynb new file mode 100644 index 0000000..d27a759 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-foreign_keys.ipynb @@ -0,0 +1,417 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.foreign_keys()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve information about the columns that participate in foreign keys that reference a table." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.foreign_keys( IBM_DBConnection `*`connection,`*` string `*`qualifierName,`*` string `*`schemaName,`*` string `*`tableName`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__        : A valid Db2 server or database connection. \n", + "* __qualifierName__    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value `None` or an empty string (`''`) for Db2 databases on other operating systems. \n", + "* __schemaName__     : The name of the schema that contains the table(s) that foreign key information is to be obtained for. To use the schema associated with the current connection, provide the value `None`.\n", + "* __tableName__          : The name of the table(s) that foreign key information is to be obtained for. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return Values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an IBM_DBStatement with a result set that contains the following information:

\n", + "\n", + " * `PK_NAME`                : The name of the primary key.\n", + " * `PKTABLE_CAT`        : The name of the catalog associated with the schema and table that contains the primary key; Db2 does not use catalogs so this field will always contain the value `None`. *(Db2 databases on OS/390 or z/OS servers can return information in this field.)*\n", + " * `PKTABLE_SCHEM`    : The name of the schema for the table that contains the primary key.\n", + " * `PKTABLE_NAME`      : The name of the table that contains the primary key.\n", + " * `PKCOLUMN_NAME`    : The name of a primary key column.\n", + " * `FK_NAME`                : The name of the foreign key.\n", + " * `FKTABLE_CAT`        : The name of the catalog associated with the schema and table that contains the foreign key; Db2 does not use catalogs so this field will always contain the value `None`. *(Db2 databases on OS/390 or z/OS servers can return information in this field.)*\n", + " * `FKTABLE_SCHEM`    : The name of the schema for the table that contains the foreign key.\n", + " * `FKTABLE_NAME`      : The name of the table that contains the foreign key.\n", + " * `FKCOLUMN_NAME`    : The name of a foreign key column. \n", + " * `KEY_SEQ`                : The __FKCOLUMN_NAME__ column's ordinal position in the foreign key, starting from 1.\n", + " * `UPDATE_RULE`        : The action to be applied to the foreign key when an `UPDATE` operation is performed.\n", + " * `DELETE_RULE`        : The action to be applied to the foreign key when a `UDELETE` operation is performed.\n", + " * `DEFERRABILITY`    : Indication of whether the foreign key is deferred initially and applied later, applied immediately, or cannot be deferred.

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.foreign_keys__ API is used to retrieve information about the columns that participate in foreign keys that reference a table.

\n", + " \n", + "The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Obtaining information about tables in the DB2INST1 schema ... Done!\n", + "\n", + "Obtaining information about foreign keys created for the DB2INST1.PROJECT table ... Done!\n", + "\n", + "Foreign key 1 details:\n", + "______________________________________________\n", + "Primary key name : PK_PROJECT\n", + " Table schema : DB2INST1\n", + " Table name : PROJECT\n", + " Column name : PROJNO\n", + "Foreign key name : RPAP\n", + " Table schema : DB2INST1\n", + " Table name : PROJACT\n", + " Column name : PROJNO\n", + " Column number : 1\n", + " UPDATE rule used : NO_ACTION\n", + " DELETE rule used : RESTRICT\n", + " Deferability : NOT_DEFERRABLE\n", + "\n", + "Foreign key 2 details:\n", + "______________________________________________\n", + "Primary key name : PK_PROJECT\n", + " Table schema : DB2INST1\n", + " Table name : PROJECT\n", + " Column name : PROJNO\n", + "Foreign key name : RPP\n", + " Table schema : DB2INST1\n", + " Table name : PROJECT\n", + " Column name : MAJPROJ\n", + " Column number : 1\n", + " UPDATE rule used : NO_ACTION\n", + " DELETE rule used : CASCADE\n", + " Deferability : NOT_DEFERRABLE\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-foreign_keys.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.foreign_keys() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.tables() #\n", + "# ibm_db.fetch_assoc() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "schemaName = userID.upper()\n", + "tableName = \"PROJECT\"\n", + "resultSet = False\n", + "dataRecord = False\n", + "foreignKeyRules = {0 : \"CASCADE\", 1 : \"RESTRICT\", 2 : \"SET_NULL\", 3 : \"NO_ACTION\", \n", + " 4 : \"SET_DEFAULT\"}\n", + "deferability = {5 : \"INITIALLY_DEFERRED\", 6 : \"INITIALLY_IMMEDIATE\", \n", + " 7 : \"NOT_DEFERRABLE\"}\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Retrieve Information About All Of The Tables In The Current User's Schema\n", + "print(\"Obtaining information about tables in the \" + schemaName + \" schema ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.tables(dbConnection, None, schemaName, None, 'TABLE')\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit\n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired\\n.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# As Long As There Are Records (That Were Produced By The ibm_db.tables API), ... \n", + "tableList = []\n", + "noData = False\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Store The Table Name Retrieved In A Python List (This List Will Be Used\n", + " # Later To Skip Records Associated With Aliases)\n", + " else:\n", + " tableList.append(dataRecord['TABLE_NAME'])\n", + "\n", + "# Attempt To Retrieve Information About All Of The Foreign Keys That Have Been Defined For \n", + "# The Table Specified\n", + "print(\"Obtaining information about foreign keys created for \", end=\"\")\n", + "print(\"the \" + schemaName + \".\" + tableName + \" table ... \", end=\"\")\n", + "resultSet = False\n", + "try:\n", + " resultSet = ibm_db.foreign_keys(dbConnection, None, schemaName, tableName)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit\n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired\\n.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# As Long As There Are Records (That Were Produced By The ibm_db.foreign_keys API), ...\n", + "noData = False\n", + "loopCounter = 1\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Data Retrieved (Skip Information For Aliases)\n", + " else:\n", + "\n", + " # If The Current Data Record Is For A Table Alias, Ignore It\n", + " if not dataRecord['FKTABLE_NAME'] in tableList:\n", + " continue\n", + "\n", + " # Display Record Header Information\n", + " print(\"Foreign key \" + str(loopCounter) + \" details:\")\n", + " print(\"______________________________________________\")\n", + "\n", + " # Display The Information Stored In The Data Record Retrieved\n", + " print(\"Primary key name : {}\" .format(dataRecord['PK_NAME']))\n", + " print(\" Table schema : {}\" .format(dataRecord['PKTABLE_SCHEM']))\n", + " print(\" Table name : {}\" .format(dataRecord['PKTABLE_NAME']))\n", + " print(\" Column name : {}\" .format(dataRecord['PKCOLUMN_NAME']))\n", + " print(\"Foreign key name : {}\" .format(dataRecord['FK_NAME']))\n", + " print(\" Table schema : {}\" .format(dataRecord['FKTABLE_SCHEM']))\n", + " print(\" Table name : {}\" .format(dataRecord['FKTABLE_NAME']))\n", + " print(\" Column name : {}\" .format(dataRecord['FKCOLUMN_NAME']))\n", + " print(\" Column number : {}\" .format(dataRecord['KEY_SEQ']))\n", + " print(\" UPDATE rule used : \", end=\"\")\n", + " print(foreignKeyRules.get(dataRecord['UPDATE_RULE']))\n", + " print(\" DELETE rule used : \", end=\"\")\n", + " print(foreignKeyRules.get(dataRecord['DELETE_RULE']))\n", + " print(\" Deferability : \", end=\"\")\n", + " print(deferability.get(dataRecord['DEFERRABILITY']))\n", + "\n", + " # Increment The loopCounter Variable And Print A Blank Line To Separate Foreign Key\n", + " # Records From Each Other\n", + " loopCounter += 1\n", + " print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-free_result.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-free_result.ipynb new file mode 100644 index 0000000..fc670be --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-free_result.ipynb @@ -0,0 +1,386 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.free_result()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Free all system resources associated with an `IBM_DBStatement` object." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.free_result( IBM_DBStatement `*`statement`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : System resources associated with the `IBM_DBStatement` object were freed. \n", + "* `False`    : System resources associated with the `IBM_DBStatement` object could not be freed." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.free_result()__ API is used to stop all processing, discard all pending results, close any open cursors, and free all memory associated with a specific `IBM_DBStatement` object. This work is done automatically when an application ends and control is returned to the operating system. However, the __ibm_db.free_result()__ API provides a way to explicitly perform these operations, when appropriate, while an application is running. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Preparing the SQL statement \"SELECT * FROM employee WHERE edlevel > 17\" ... Done!\n", + "\n", + "Executing the prepared SQL statement ... Done!\n", + "\n", + "Unable to obtain information about the number of rows returned.\n", + "\n", + "Freeing system resources associated with the prepared statement ... Done!\n", + "\n", + "Turning SQL_ATTR_ROWCOUNT_PREFETCH behavior ON ... Done!\n", + "\n", + "Executing the prepared SQL statement again ... Done!\n", + "\n", + "Number of rows returned by the query: 9\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-free_result.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.free_result() API #\n", + "# to free system resources associated with a prepared SQL statement. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.prepare() #\n", + "# ibm_db.execute() #\n", + "# ibm_db.num_rows() #\n", + "# ibm_db.set_option() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "preparedStmt = False\n", + "resultSet = False\n", + "returnCode = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT * FROM employee WHERE edlevel > 17\"\n", + "\n", + "# Prepare The SQL Statement Just Defined\n", + "print(\"Preparing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit\n", + "if preparedStmt is False:\n", + " print(\"\\nERROR: Unable to prepare the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Execute The SQL Statement Just Prepared\n", + "print(\"Executing the prepared SQL statement ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.execute(preparedStmt)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Just Executed\n", + "# (This Information Should Not Be Available)\n", + "try:\n", + " numRows = ibm_db.num_rows(preparedStmt)\n", + "except Exception:\n", + " pass\n", + " \n", + "# Display An Appropriate Message, Based On The Information Returned\n", + "if numRows <= 0:\n", + " print(\"Unable to obtain information about the number of rows returned.\\n\")\n", + "else:\n", + " print(\"Number of rows returned by the query: \" + str(numRows) + \"\\n\")\n", + "\n", + "# Free System Resources That Are Associated With The Prepared Statement And Result Set Produced\n", + "print(\"Freeing system resources associated with the prepared statement ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.free_result(preparedStmt)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Appropriate System Resources Could Not Be Freed, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to free the appropriate system resources.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Create A Dictionary That Contains The Value Needed To Turn Row Prefetch Behavior On;\n", + "# This Enables Db2 To Determine The Number Of Rows That Are Returned By A Query (So The\n", + "# Entire Result Set Can Be Prefetched Into Memory, When Possible) \n", + "stmtOption = {ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON}\n", + "\n", + "# Attempt To Set The Statement Option Specified\n", + "print(\"Turning SQL_ATTR_ROWCOUNT_PREFETCH behavior ON ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.set_option(preparedStmt, stmtOption, 0)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Statement Option Could Not Be Set, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to set the statement option specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Execute The Prepared SQL Statement Again\n", + "print(\"Executing the prepared SQL statement again ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.execute(preparedStmt)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Again\n", + "# (This Time, The Information Should Be Available)\n", + "try:\n", + " numRows = ibm_db.num_rows(preparedStmt)\n", + "except Exception:\n", + " pass\n", + "\n", + "# Display An Appropriate Message, Based On The New Information Returned\n", + "if numRows <= 0:\n", + " print(\"Unable to obtain information about the number of rows returned.\\n\")\n", + "else:\n", + " print(\"Number of rows returned by the query: \" + str(numRows) + \"\\n\")\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-get_option.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-get_option.ipynb new file mode 100644 index 0000000..7dd9ab4 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-get_option.ipynb @@ -0,0 +1,518 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.get_option()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve the current value of a connection or statement option (attribute)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`mixed ibm_db.get_option( mixed `*`resource,`*` int `*`options,`*` int `*`resourceType`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*resource*__            : A valid `IBM_DBConnection` or `IBM_DBStatement` object. \n", + "* __options__              : A valid key for the attribute whose value is to be retrieved. Valid keys for `IBM_DBConnection` objects are:

\n", + " \n", + " * `ibm_db.SQL_ATTR_AUTOCOMMIT`                               : Indicates whether __AUTOCOMMIT__ mode is being used or not; `ibm_db.SQL_AUTOCOMMIT_ON` will be returned if __AUTOCOMMIT__ behavior is __ON__ and `ibm_db.SQL_AUTOCOMMIT_OFF` will be returned if it is __OFF__.\n", + " * `ibm_db.SQL_ATTR_CASE`                                           : The case that column names will be returned in; `ibm_db.CASE_NATURAL` will cause column names to be returned in natural case, `ibm_db.CASE_LOWER` will cause them to be returned in lower case, and `ibm_db.CASE_UPPER` will cause them to be returned in upper case. *(This attribute can only be used with Db2 databases on OS/390 or z/OS servers.)*\n", + " * `ibm_db.SQL_ATTR_CURRENT_SCHEMA`                       : The name of the schema that is used, by default, when operations that require a schema name are performed and no schema name is provided.\n", + " * `ibm_db.SQL_ATTR_INFO_ACCTSTR`                           : The client accounting string (that may have been sent to the currently connected Db2 server or database).\n", + " * `ibm_db.SQL_ATTR_INFO_APPLNAME`                         : The client application name (that may have been sent to the currently connected Db2 server or database).\n", + " * `ibm_db.SQL_ATTR_INFO_PROGRAMNAME`                   : The name of the application being run (on the client).\n", + " * `ibm_db.SQL_ATTR_INFO_USERID`                             : The client user ID (accounting user ID) that may have been sent to the currently connected Db2 server or database. This information is used for identification purposes only—not for authentication.\n", + " * `ibm_db.SQL_ATTR_INFO_WRKSTNNAME`                     : The client workstation name (that may have been sent to the currently connected Db2 server or database).\n", + " * `ibm_db.SQL_ATTR_USE_TRUSTED_CONTEXT`             : Indicates whether the connection to a Db2 server or database being used is treated as a trusted connection; `ibm_db.SQL_TRUE` indicates a trusted connection is being used and `ibm_db.SQL_FALSE` indicates a trusted connection is not. \n", + " * `ibm_db.SQL_ATTR_TRUSTED_CONTEXT_USERID`       : The client user ID (accounting user ID) that the trusted connection being used has been switched to. \n", + " * `ibm_db.SQL_ATTR_TRUSTED_CONTEXT_PASSWORD`   : The password for the __ibm_db.SQL_ATTR_TRUSTED_CONTEXT_USERID__ user.

\n", + " \n", + " Valid keys for `IBM_DBStatement` objects are:

\n", + " \n", + " * `ibm_db.SQL_ATTR_CURSOR_TYPE`                             : The type of cursor that is being used to process result sets. Valid values are:\n", + " * `ibm_db.SQL_CURSOR_FORWARD_ONLY`                 : A forward only cursor is being used.\n", + " * `ibm_db. SQL_CURSOR_KEYSET_DRIVEN`             : A keyset-driven cursor is being used.\n", + " * `ibm_db.SQL_CURSOR_STATIC`                             : A static cursor is being used.\n", + " * `ibm_db.SQL_CURSOR_DYNAMIC`                           : A dynamic, scrollable cursor is being used. Dynamic cursors are only supported by Db2 for z/OS servers.\n", + " * `ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH`                 : Identifies whether Db2 will try to determine the number of rows that will be returned by a query; `ibm_db.SQL_ROWCOUNT_PREFETCH_ON` will be returned if this behavior is turned __ON__ and `ibm_db.SQL_ROWCOUNT_PREFETCH_OFF` if it is turned __OFF__.\n", + " * `ibm_db.SQL_ATTR_QUERY_TIMEOUT`                         : The number of seconds Db2 will wait for an SQL statement to execute before aborting and returning to the application. A value of __0__ indicates applications will wait indefinitely for the server to complete execution.

\n", + " \n", + "* __resourceType__    : Identifies whether the value provided in the __*resource*__ parameter is an `IBM_DBConnection` object or an `IBM_DBStatement` object. Valid values for this parameter are:

\n", + " \n", + " * `0`   : The __*resource*__ parameter contains a valid `IBM_DBStatement` object.\n", + " * `1`   : The __*resource*__ parameter contains a valid `IBM_DBConnection` object." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return Values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, the current setting of the option specified.\n", + "* If __unsuccessful__, a Python interpreter error." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.get_option__ API is used to retrieve the current setting of a specific connection or statement option (attribute)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Examples:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###     Example 1: Get connection options" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the 'SAMPLE' database ... Done!\n", + "\n", + "Connection option settings:\n", + "\n", + "OPTION SETTING\n", + "_________________________ ____________________\n", + "SQL_ATTR_AUTOCOMMIT 1\n", + "SQL_ATTR_CURRENT_SCHEMA db2inst1\n", + "SQL_ATTR_INFO_PROGRAMNAME ibm_db-get_option.py\n", + "\n", + "Disconnecting from the 'SAMPLE' database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-get_option_CONNECTION.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.get_option() API to #\n", + "# obtain the values that have been assigned to some of the connection options #\n", + "# available. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.connect() #\n", + "# ibm_db.close() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "\n", + "# Create A Dictionary That Contains Connection Options That Can Be Set Before A Database\n", + "# Connection Is Established\n", + "connectOptions = {ibm_db.SQL_ATTR_AUTOCOMMIT : ibm_db.SQL_AUTOCOMMIT_ON,\n", + " ibm_db.SQL_ATTR_CURRENT_SCHEMA : 'db2inst1',\n", + " ibm_db.SQL_ATTR_INFO_PROGRAMNAME : 'ibm_db-get_option.py'}\n", + "\n", + "# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database\n", + "# Is About To Be Made\n", + "print(\"\\nConnecting to the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + "\n", + "# Construct The String That Will Be Used To Establish A Db2 Database Connection\n", + "connString = \"ATTACH=FALSE\" # Attach To A Database; Not A Server\n", + "connString += \";DATABASE=\" + dbName # Required To Connect To A Database \n", + "connString += \";PROTOCOL=TCPIP\"\n", + "connString += \";UID=\" + userID\n", + "connString += \";PWD=\" + passWord\n", + "\n", + "# Attempt To Establish A Connection To The Database Specified (And Set The Appropriate\n", + "# Connection Options) \n", + "try:\n", + " dbConnection = ibm_db.connect(connString, '', '', connectOptions)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit\n", + "if dbConnection is None:\n", + " print(\"\\nERROR: Unable to connect to the \\'\" + dbName + \"\\' database.\")\n", + " print(\"Connection string used: \" + connString + \"\\n\")\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Connection option settings:\\n\")\n", + "print(\"OPTION SETTING\")\n", + "print(\"_________________________ ____________________\")\n", + "\n", + "# Retrieve And Display The Ordinal Value For The Current AUTOCOMMIT Setting\n", + "value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_AUTOCOMMIT, 1)\n", + "print(\"SQL_ATTR_AUTOCOMMIT \", end=\"\")\n", + "print(ord(value))\n", + "\n", + "# Retrieve And Display The Schema Name That Was Set During The Connection\n", + "value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_CURRENT_SCHEMA, 1)\n", + "print(\"SQL_ATTR_CURRENT_SCHEMA \" + value)\n", + "\n", + "# Retrieve And Display The Program Name That Was Set During The Connection\n", + "value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_PROGRAMNAME, 1)\n", + "print(\"SQL_ATTR_INFO_PROGRAMNAME \" + value)\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Attempt To Close The Db2 Database Connection That Was Opened Earlier\n", + "if not dbConnection is None:\n", + " print(\"Disconnecting from the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.close(dbConnection)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + dbName + \" database.\")\n", + " exit(-1)\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###     Example 2: Get statement option" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT * FROM employee WHERE edlevel > 17\" ... Done!\n", + "\n", + "Obtaining information about the type of cursor being used ... Done!\n", + "\n", + "Type of cursor specified : Static (SQL_CURSOR_STATIC)\n", + "Type of cursor being used: Static (SQL_CURSOR_STATIC)\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-get_option_STATEMENT.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.get_option() API to #\n", + "# assign a value to one of the statement options available. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "cursorType = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Create A Dictionary That Contains Values For All Of The Statement Options That Can Be Set \n", + "stmtOptions = {ibm_db.SQL_ATTR_CURSOR_TYPE : ibm_db.SQL_CURSOR_STATIC,\n", + " ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON,\n", + " ibm_db.SQL_ATTR_QUERY_TIMEOUT : 10}\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT * FROM employee WHERE edlevel > 17\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement, stmtOptions)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified\n", + "print(\"Obtaining information about the type of cursor being used ... \", end=\"\")\n", + "try:\n", + " cursorType = ibm_db.get_option(resultSet, ibm_db.SQL_ATTR_CURSOR_TYPE, 0)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If Information About The Cursor Could Not Be Obtained, Display An Error Message And Exit \n", + "if cursorType is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified\n", + "print(\"Type of cursor specified : Static (SQL_CURSOR_STATIC)\")\n", + "print(\"Type of cursor being used: \", end=\"\")\n", + "\n", + "if cursorType == ibm_db.SQL_CURSOR_FORWARD_ONLY:\n", + " print(\"Forward only (SQL_CURSOR_FORWARD_ONLY)\\n\")\n", + "elif cursorType == ibm_db.SQL_CURSOR_KEYSET_DRIVEN:\n", + " print(\"Keyset driven (SQL_CURSOR_KEYSET_DRIVEN)\\n\")\n", + "elif cursorType == ibm_db.SQL_CURSOR_DYNAMIC:\n", + " print(\"Dynamic (SQL_CURSOR_DYNAMIC)\\n\")\n", + "elif cursorType == ibm_db.SQL_CURSOR_STATIC:\n", + " print(\"Static (SQL_CURSOR_STATIC)\\n\")\n", + "else:\n", + " print(\"Unknown\\n\")\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-next_result.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-next_result.ipynb new file mode 100644 index 0000000..1dee937 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-next_result.ipynb @@ -0,0 +1,447 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.next_result()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve the next result set returned by a stored procedure." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.next_result( IBM_DBStatement `*`statement`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object that contains multiple result sets." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, a new `IBM_DBStatement` object that contains the next result set returned by a stored procedure — provided another result set was available.\n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.next_result()__ API is used to retrieve the next result set that is returned by a stored procedure — provided the stored procedure returns more than one result set. (A stored procedure can return zero or more result sets.)

\n", + " \n", + "While data in the first result set returned by a stored procedure can be retrieved the same way data in a result set produced by a simple __SELECT__ statement can be retrieved, data in subsequent result sets returned cannot be accessed until the __ibm_db.next_result()__ API is used to copy the next result set to a uniquely named Python variable." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Creating an SQL stored procedure named \"HIGH_EARNERS\" ... Done!\n", + "\n", + "Executing the HIGH_EARNERS procedure & retrieving the first result set produced ... Done!\n", + "\n", + "Retrieving the second result set produced by the HIGH_EARNERS procedure ... Done!\n", + "\n", + "Retrieving the third result set produced by the HIGH_EARNERS procedure ... Done!\n", + "\n", + "Information retrieved:\n", + "\n", + " Result set 1 details:\n", + "\n", + " FIRSTNME LASTNAME SALARY JOB\n", + " ______________ __________________ __________ ________\n", + " REBA JOHN $ 69840.00 DESIGNER \n", + " WILLIAM JONES $ 68270.00 DESIGNER \n", + " KIYOSHI YAMAMOTO $ 64680.00 DESIGNER \n", + " ELIZABETH PIANKA $ 62250.00 DESIGNER \n", + "\n", + " Result set 2 details:\n", + "\n", + " FIRSTNME LASTNAME SALARY JOB\n", + " ______________ __________________ __________ ________\n", + " DELORES QUINTANA $ 73800.00 ANALYST \n", + " HEATHER NICHOLLS $ 68420.00 ANALYST \n", + " KIM NATZ $ 68420.00 ANALYST \n", + "\n", + " Result set 3 details:\n", + "\n", + " FIRSTNME LASTNAME SALARY JOB\n", + " ______________ __________________ __________ ________\n", + " VINCENZO LUCCHESSI $ 66500.00 SALESREP \n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-next_result.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.next_result() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.callproc() #\n", + "# ibm_db.fetch_tuple() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "spName = \"HIGH_EARNERS\"\n", + "returnCode = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Used To Create A New Stored Procedure That\n", + "# Returns Three Result Sets\n", + "sqlStatement = \"CREATE OR REPLACE PROCEDURE \" + spName + \" \"\n", + "sqlStatement += \"LANGUAGE SQL \"\n", + "sqlStatement += \"DYNAMIC RESULT SETS 3 \"\n", + "sqlStatement += \"READS SQL DATA \"\n", + "sqlStatement += \"NO EXTERNAL ACTION \"\n", + "sqlStatement += \"BEGIN \"\n", + "sqlStatement += \" DECLARE avgSalary INT DEFAULT 0; \"\n", + "sqlStatement += \" DECLARE c1 CURSOR WITH RETURN FOR \"\n", + "sqlStatement += \" SELECT firstnme, lastname, salary, job FROM employee \"\n", + "sqlStatement += \" WHERE job = 'DESIGNER' AND \"\n", + "sqlStatement += \" salary > avgSalary \"\n", + "sqlStatement += \" ORDER BY salary DESC; \"\n", + "sqlStatement += \" DECLARE c2 CURSOR WITH RETURN FOR \"\n", + "sqlStatement += \" SELECT firstnme, lastname, salary, job FROM employee \"\n", + "sqlStatement += \" WHERE job = 'ANALYST' AND \"\n", + "sqlStatement += \" salary > avgSalary \"\n", + "sqlStatement += \" ORDER BY salary DESC; \"\n", + "sqlStatement += \" DECLARE c3 CURSOR WITH RETURN FOR \"\n", + "sqlStatement += \" SELECT firstnme, lastname, salary, job FROM employee \"\n", + "sqlStatement += \" WHERE job = 'SALESREP' AND \"\n", + "sqlStatement += \" salary > avgSalary \"\n", + "sqlStatement += \" ORDER BY salary DESC; \"\n", + "sqlStatement += \" SELECT INT(AVG(salary)) INTO avgSalary FROM employee; \"\n", + "sqlStatement += \" OPEN c1; \"\n", + "sqlStatement += \" OPEN c2; \"\n", + "sqlStatement += \" OPEN c3; \"\n", + "sqlStatement += \"END\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Creating an SQL stored procedure named \\\"\" + spName + \"\\\" ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Execute The Stored Procedure Just Created\n", + "resultSet_1 = None\n", + "print(\"Executing the \" + spName + \" procedure & retrieving the first \", end=\"\")\n", + "print(\"result set produced ... \", end=\"\")\n", + "try:\n", + " resultSet_1 = ibm_db.callproc(dbConnection, spName)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Stored Procedure Specified Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet_1 is None:\n", + " print(\"\\nERROR: Unable to execute the stored procedure specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message; Then Format And Display The Data Values Returned\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Retrieve The Second Result Set From The Stored Procedure Just Executed\n", + "print(\"Retrieving the second result set produced by the \" + spName, end=\"\")\n", + "print(\" procedure ... \", end=\"\")\n", + "resultSet_2 = False\n", + "try:\n", + " resultSet_2 = ibm_db.next_result(resultSet_1)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Second Result Set Could Not Be Retrieved, Display An Error Message And Exit \n", + "if resultSet_2 is False:\n", + " print(\"\\nERROR: Unable to retrieve the second result set returned by the stored procedure.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\") \n", + "\n", + "# Retrieve The Third Result Set From The Stored Procedure Just Executed\n", + "print(\"Retrieving the third result set produced by the \" + spName, end=\"\")\n", + "print(\" procedure ... \", end=\"\")\n", + "resultSet_3 = False\n", + "try:\n", + " resultSet_3 = ibm_db.next_result(resultSet_1)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Third Result Set Could Not Be Retrieved, Display An Error Message And Exit \n", + "if resultSet_3 is False:\n", + " print(\"\\nERROR: Unable to retrieve the third result set returned by the stored procedure.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Information retrieved:\")\n", + "\n", + "# As Long As There Are Records To Retrieve, ... \n", + "noData = False\n", + "loopCounter = 1\n", + "printHeader = True\n", + "dataRecord = True\n", + "while noData is False:\n", + "\n", + " # Display Record Header Information\n", + " if printHeader is True:\n", + " print(\"\\n Result set \" + str(loopCounter) + \" details:\\n\")\n", + " print(\" FIRSTNME LASTNAME SALARY JOB\")\n", + " print(\" ______________ __________________ __________ ________\")\n", + " printHeader = False\n", + "\n", + " # Retrieve A Record From The Appropriate Result Set And Store It In A Python Tuple\n", + " if loopCounter is 1:\n", + " try:\n", + " dataRecord = ibm_db.fetch_tuple(resultSet_1)\n", + " except:\n", + " pass\n", + " elif loopCounter is 2:\n", + " try:\n", + " dataRecord = ibm_db.fetch_tuple(resultSet_2)\n", + " except:\n", + " pass\n", + " elif loopCounter is 3:\n", + " try:\n", + " dataRecord = ibm_db.fetch_tuple(resultSet_3)\n", + " except:\n", + " pass\n", + "\n", + " # If The Record Could Not Be Retrieved Or If There Was No Data To Retrieve, Increment The\n", + " # Loop Counter Variable And Set The Appropriate Variables To True \n", + " if dataRecord is False:\n", + " loopCounter += 1\n", + " printHeader = True\n", + " dataRecord = True\n", + " \n", + " # If There Is No More Data To Retrieve, Set The \"No Data\" Flag And Exit The Loop \n", + " if loopCounter is 4:\n", + " noData = True\n", + " else:\n", + " continue\n", + " \n", + " # Otherwise, Extract And Display The Information Stored In The Data Record Retrieved\n", + " else:\n", + " print(\" {:<14}\" .format(dataRecord[0]), end=\"\")\n", + " print(\" {:<18}\" .format(dataRecord[1]), end=\"\")\n", + " print(\" ${:>9}\" .format(dataRecord[2]), end=\"\")\n", + " print(\" {:<10}\" .format(dataRecord[3]))\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-num_fields.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-num_fields.ipynb new file mode 100644 index 0000000..7424ab2 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-num_fields.ipynb @@ -0,0 +1,295 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.num_fields()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Determine the number of columns that exist in a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`int ibm_db.num_fields( IBM_DBStatement `*`statement`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object that contains a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an integer representing the number of columns (fields) that exist in the result associated with the `IBM_DBStatement` object specified.\n", + "* If __unsuccessful__ or if the `IBM_DBStatement` object specified is not valid, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.num_fields()__ API is used to determine the number of columns that exist in a result set. Having this information can be useful when retrieving and processing result sets that were produced by dynamically generated queries, or were returned by stored procedures." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT * FROM project WHERE prstaff < 5\" ... Done!\n", + "\n", + "Examining the result set produced ... Done!\n", + "\n", + "There are 8 columns in the result set produced by the query.\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-num_fields.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db-num_fields() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "numColumns = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT * FROM project WHERE prstaff < 5\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed\n", + "print(\"Examining the result set produced ... \", end=\"\")\n", + "try:\n", + " numColumns = ibm_db.num_fields(resultSet)\n", + "except Exception:\n", + " pass\n", + " \n", + "# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error\n", + "# Message And Exit \n", + "if numColumns is False:\n", + " print(\"\\nERROR: Unable to obtain information about the result set produced.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display The Information Retrieved\n", + "print(\"There are \" + str(numColumns) + \" columns in the result set produced by the query.\\n\")\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-num_rows.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-num_rows.ipynb new file mode 100644 index 0000000..8e727d0 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-num_rows.ipynb @@ -0,0 +1,352 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.num_rows()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Determine how many rows were inserted, updated, or deleted by an SQL statement." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`int ibm_db.num_rows( IBM_DBStatement `*`statement`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object associated with an __INSERT__, __UPDATE__, or __DELETE__ SQL statement." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an integer representing the number of rows that were affected by the last SQL operation performed using the `IBM_DBStatement` object specified.\n", + "* If __unsuccessful__, nothing." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.num_rows()__ API is used to return the number of rows that were affected by an __INSERT__, __UPDATE__, or __DELETE__ operation. And, in some cases, it can be used to indicate how many rows will be returned by a __SELECT__ statement. (For example, if the __ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH__ statement option is turned __ON__ or a scrollable cursor is used.)

\n", + "\n", + "It is important to note that the overhead associated with scrollable cursors can significantly degrade application performance. So, if the only reason you would use a scrollable cursor would be to determine how many rows could be returned by a __SELECT__ statement, you would be better off using a forward-only cursor and issuing a \"__SELECT COUNT(\\*)__\" statement (with the same predicates as your intended __SELECT__ statement) and retrieving the value returned." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Turning AUTOCOMMIT behavior OFF ... Done!\n", + "\n", + "Preparing the SQL statement \"INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)\" ... Done!\n", + "\n", + "Executing the prepared SQL statement ... Done!\n", + "\n", + "Number of rows affected by the INSERT operation: 3\n", + "\n", + "Backing out changes made to the database ... Done!\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-num_rows.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db-num_rows() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.autocommit() #\n", + "# ibm_db.prepare() #\n", + "# ibm_db.exec_many() #\n", + "# ibm_db.exec_rollback() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "returnCode = False\n", + "preparedStmt = False\n", + "numRows = False\n", + "resultSet = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + " \n", + "# Turn Autocommit Behavior OFF\n", + "print(\"Turning AUTOCOMMIT behavior OFF ... \", end=\"\")\n", + "returnCode = ibm_db.autocommit(dbConnection, 0)\n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to turn off AUTOCOMMIT behavior.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + " \n", + "# Define The INSERT Statement (With Parameter Markers) That Is To Be Used To Add Data\n", + "# To The DEPARTMENT Table\n", + "sqlStatement = \"INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)\"\n", + "\n", + "# Prepare The SQL Statement Just Defined\n", + "print(\"Preparing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit\n", + "if preparedStmt is False:\n", + " print(\"\\nERROR: Unable to prepare the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Create A List Of Data Values That Are To Be Supplied For The Parameter Markers Coded\n", + "# In The INSERT Statement Specified\n", + "pmValues = (('K22', 'SALES', '000110'), \n", + " ('L22', 'FINANCE', '000120'), \n", + " ('M22', 'HUMAN RESOURCES', '000130'))\n", + "\n", + "# Execute The SQL Statement Just Prepared\n", + "print(\"Executing the prepared SQL statement ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.execute_many(preparedStmt, pmValues) \n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message And Display The Number Of Records Added\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Find Out How Many Rows Were Affected By The INSERT Operation\n", + "try:\n", + " numRows = ibm_db.num_rows(preparedStmt)\n", + "except Exception:\n", + " pass\n", + " \n", + "# If Information About The Number Rows Affected Could Not Be Obtained, Display An Error\n", + "# Message And Exit \n", + "if numRows is False:\n", + " print(\"\\nERROR: Unable to obtain information about the number of rows affected.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Display The Information Obtained\n", + "else:\n", + " print(\"Number of rows affected by the INSERT operation: \" + str(numRows) + \"\\n\")\n", + "\n", + "# Back Out The Changes Just Made To The Database\n", + "print(\"Backing out changes made to the database ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.rollback(dbConnection)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Rollback Operation Could Not Be Performed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to roll back the previous operation.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + " \n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-pconnect.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-pconnect.ipynb new file mode 100644 index 0000000..35c14d7 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-pconnect.ipynb @@ -0,0 +1,645 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.pconnect()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Establish a persistent connection to an IBM Db2 server or database." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBConnection ibm_db.pconnect( string `*`connectionInfo,`*` string `*`userID,`*` string `*`userPassword`*` [, dictionary `*`options`*` ] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connectionInfo*__    : A valid Db2 database alias (if the database has been cataloged in the system database directory) *or* a connection string with the format `DRIVER={IBM DB2 ODBC DRIVER};ATTACH=connType;DATABASE=dbName;HOSTNAME=hostName;PORT=port;PROTOCOL=TCPIP;UID=userName;PWD=password` where:

\n", + " \n", + " * `connType`     : Specifies whether the connection is to be made to a Db2 server or database; `TRUE` indicates the connection is to be made to a Db2 server and `FALSE` indicates the connection is to be made to a database.\n", + " * `dbName`         : The name of the Db2 server or database the connection is to be made to. *This option is only required when connecting to a Db2 database.*\n", + " * `hostName`     : The host name or IP address of the Db2 server the connection is to be made to. (The hostname is the name of the Db2 server, as it is known to the TCP/IP network.) *This option is only required when connecting to a Db2 server.*\n", + " * `port`             : The port number that receives Db2 connections on the server the connection is to be made to. (Port number __50000__ is used by default.) *This option is only required when connecting to a Db2 server.*\n", + " * `userName`     : The user name/ID that is to be used for authentication when the connection is established.\n", + " * `password`     : The password that corresponds to the user name/ID specified in the __*userName*__ parameter.

\n", + " \n", + "* __*userID*__                   : The user ID that is to be used for authentication when a connection is established. *If a Db2 database alias is NOT provided in the __connectionInfo__ parameter, this parameter must contain an empty string.*\n", + "* __*userPassword*__      : The password that corresponds to the user ID specified in the __*userPassword*__ parameter. *If a Db2 database alias is NOT provided in the __connectionInfo__ parameter, this parameter must contain an empty string.* \n", + "* __*options*__                 : A dictionary containing key-value pairs for the attributes that are to be set before a connection is established. Valid keys for `IBM_DBConnection` objects are:

\n", + " \n", + " * `ibm_db.SQL_ATTR_AUTOCOMMIT`                     : Specifies whether __AUTOCOMMIT__ mode is to be used or not; `ibm_db.SQL_AUTOCOMMIT_ON` will turn __AUTOCOMMIT__ behavior __ON__ and `ibm_db.SQL_AUTOCOMMIT_OFF` will turn it __OFF__.\n", + " * `ibm_db.SQL_ATTR_CASE`                                 : The case that column names will be returned in; `ibm_db.CASE_NATURAL` will cause column names to be returned in natural case, `ibm_db.CASE_LOWER` will cause them to be returned in lower case, and `ibm_db.CASE_UPPER` will cause them to be returned in upper case. *(This attribute can only be used with Db2 databases on OS/390 or z/OS servers.)* \n", + " * `ibm_db.SQL_ATTR_CURRENT_SCHEMA`             : The name of the schema to use, by default, when performing operations that require a schema name and one is not provided.\n", + " * `ibm_db.SQL_ATTR_USE_TRUSTED_CONTEXT`   : Specifies whether the connection to a Db2 server or database is to be treated as a trusted connection; `ibm_db.SQL_TRUE` indicates the connection can be trusted and `ibm_db.SQL_FALSE` indicates the connection should not to be treated as a trusted connection.

" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, a valid `IBM_DBConnection` object.\n", + "* If __unsuccessful__, the value `None`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.pconnect()__ API is used to establish a persistent connection to an IBM Db2 server or database.

\n", + " \n", + "Unlike connections that are established using the __ibm_db.connect()__ API, persistent connections created with the __ibm_db.pconnect()__ API are not closed with the __ibm_db.close()__ API. Instead, they are returned to a process-wide connection pool (when the __ibm_db.close()__ API is executed.) Then, the next time the __ibm_db.pconnect()__ API is called, the connection pool is searched for a matching connection and if one is found, it is returned to the application — new connections are not created unless there is no connection in the pool that meets the application's needs.

\n", + " \n", + "As with the __ibm_db.connect()__ API, if a connection to a remote Db2 server or database is desired, the information needed to connect to the server (i.e., the host name, port number, and communications protocol) must be provided before a connection to either resource can be established. If a connection to a local, cataloged Db2 database is needed instead, just the alias for the database, as defined in the system database directory, must be supplied; values for the __*userID*__ and __*userPassword*__ parameters are optional. (If this API is called and just a local database alias is provided — for example, __conn = ibm_db.connect( 'SAMPLE', ' ', ' ' )__, — an attempt to establish a connection to the database will be made using the authorization ID and password for the current logged in Db2 instance user.)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Examples:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 1: Create a pool of 10 local Db2 database connections" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Establishing 10 connections to the 'SAMPLE' database ... \n", + "\n", + " Connection 1 ready!\n", + " Connection 2 ready!\n", + " Connection 3 ready!\n", + " Connection 4 ready!\n", + " Connection 5 ready!\n", + " Connection 6 ready!\n", + " Connection 7 ready!\n", + " Connection 8 ready!\n", + " Connection 9 ready!\n", + " Connection 10 ready!\n", + "\n", + "Executing the SQL statement \"SELECT * FROM department\" from Connection 5 ... Done!\n", + "\n", + "Number of rows returned by the query: 14\n", + "\n", + "Closing database Connection 5 ... Done!\n", + "(Connection 5 has been returned the pool of connections opened earlier.)\n", + "\n", + "Closing all remaining connections to the 'SAMPLE' database ... \n", + "\n", + " Connection 1 closed!\n", + " Connection 2 closed!\n", + " Connection 3 closed!\n", + " Connection 4 closed!\n", + " Connection 5 closed!\n", + " Connection 6 closed!\n", + " Connection 7 closed!\n", + " Connection 8 closed!\n", + " Connection 9 closed!\n", + " Connection 10 closed!\n", + "\n", + "All database connections have been returned the pool of connections opened earlier.\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-pconnect_DB.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.pconnect() API to #\n", + "# create a pool of connections to a local Db2 database. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.num_rows() #\n", + "# ibm_db.close() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\" # The Alias For The Cataloged, Local Database\n", + "userID = \"db2inst1\" # The Instance User ID At The Local Server\n", + "passWord = \"Passw0rd\" # The Password For The Instance User ID At The Local Server\n", + "dbConnection = list(range(10))\n", + "resultSet = False\n", + "returnCode = False\n", + "\n", + "# Construct The String That Will Be Used To Establish A Db2 Database Connection\n", + "connString = \"ATTACH=FALSE\" # Attach To A Database; Not A Server\n", + "connString += \";DATABASE=\" + dbName # Required To Connect To A Database \n", + "connString += \";PROTOCOL=TCPIP\"\n", + "connString += \";UID=\" + userID\n", + "connString += \";PWD=\" + passWord\n", + "\n", + "# Display A Status Message Indicating An Attempt To Establish Ten Connections To A Db2 \n", + "# Database Is About To Be Made\n", + "print(\"\\nEstablishing 10 connections to the \\'\" + dbName + \"\\' database ... \\n\")\n", + "\n", + "# Establish Ten Connections To The Local Db2 Database Specified\n", + "for loopCounter in range(10):\n", + "\n", + " # Attempt To Establish A Database Connection \n", + " try:\n", + " dbConnection[loopCounter] = ibm_db.pconnect(connString, '', '')\n", + " except Exception:\n", + " pass\n", + "\n", + " # If A Connection Could Not Be Established, Display An Error Message And Continue\n", + " if dbConnection[loopCounter] is None:\n", + " print(\"\\nERROR: Unable to connect to the \\'\" + dbName + \"\\' database.\")\n", + " continue\n", + "\n", + " # Otherwise, Display A \"Connection Ready\" Status Message\n", + " else:\n", + " print(\" Connection {:>2} ready!\" .format(loopCounter + 1))\n", + "\n", + "# Add A Blank Line To The End Of The List Of Connections Created\n", + "print()\n", + "\n", + "# Retrieve Data From The Database Using Connection Number Five\n", + "if not dbConnection[5] is None:\n", + "\n", + " # Define The SQL Statement That Is To Be Executed \n", + " sqlStatement = \"SELECT * FROM department\"\n", + "\n", + " # Set The Statement Option That Is To be Used When the Statement Is Executed\n", + " stmtOption = {ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON}\n", + "\n", + " # Execute The SQL Statement Just Defined (Using The Desired Option)\n", + " print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" from Connection 5 ... \", end=\"\")\n", + " currentConnection = dbConnection[5]\n", + " try:\n", + " resultSet = ibm_db.exec_immediate(currentConnection, sqlStatement, stmtOption)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The SQL Statement Could Not Be Executed, Display An Error Message And Continue\n", + " if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\\n\")\n", + "\n", + " # Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Just\n", + " # Executed (There Should Be 14 Rows)\n", + " try:\n", + " numRows = ibm_db.num_rows(resultSet)\n", + " except Exception:\n", + " pass\n", + " \n", + " # Display An Appropriate Message, Based On The Information Returned\n", + " if numRows <= 0:\n", + " print(\"Unable to obtain information about the number of rows returned.\\n\")\n", + " else:\n", + " print(\"Number of rows returned by the query: \" + str(numRows) + \"\\n\")\n", + "\n", + " # Attempt To Close The Database Connection (Connection 5)\n", + " print(\"Closing database Connection 5 ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.close(currentConnection)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Connection Was Not Closed, Display An Error Message\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + dbName + \" database.\")\n", + " \n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\")\n", + " print(\"(Connection 5 has been returned the pool of connections opened earlier.)\\n\")\n", + "\n", + "# Display A Status Message Indicating An Attempt To Close The Remaining Db2 Database \n", + "# Connections Is About To Be Made\n", + "print(\"Closing all remaining connections to the \\'\" + dbName + \"\\' database ... \\n\")\n", + "\n", + "# Attempt To Close All Of The Db2 Database Connections That Were Opened Earlier\n", + "for loopCounter in range(10):\n", + " \n", + " # If The Specified Connection Is Open, Attempt To Close It\n", + " if not dbConnection[loopCounter] is None:\n", + " try:\n", + " returnCode = ibm_db.close(dbConnection[loopCounter])\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Connection Could Not Be Closed, Display An Error Message And Continue\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + dbName + \" database.\")\n", + " continue\n", + "\n", + " # Otherwise, Display A \"Connection Closed\" Status Message\n", + " else:\n", + " print(\" Connection {:>2} closed!\" .format(loopCounter + 1))\n", + "\n", + "# Display A Status Message Indicating All Database Connections Have Been Returned To The\n", + "# Connection Pool\n", + "print(\"\\nAll database connections have been returned the pool of connections opened earlier.\\n\")\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Restart the Jupyter Notebook to clear the Db2 connection pool\n", + " (This must be done before the second example can run)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "deletable": false + }, + "outputs": [], + "source": [ + "import os\n", + "os._exit(0)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 2: Create a pool of 10 remote Db2 server connections" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Establishing 10 connections to the '197.126.80.22' server ... \n", + "\n", + " Connection 1 ready!\n", + " Connection 2 ready!\n", + " Connection 3 ready!\n", + " Connection 4 ready!\n", + " Connection 5 ready!\n", + " Connection 6 ready!\n", + " Connection 7 ready!\n", + " Connection 8 ready!\n", + " Connection 9 ready!\n", + " Connection 10 ready!\n", + "\n", + "Creating a database named MY_DB using Connection 5. Please wait.\n", + "\n", + "The database \"MY_DB\" has been created!\n", + "\n", + "Closing Db2 server Connection 5 ... Done!\n", + "(Connection 5 has been returned the pool of connections opened earlier.)\n", + "\n", + "Closing all remaining connections to the '197.126.80.22' server ... \n", + "\n", + " Connection 1 closed!\n", + " Connection 2 closed!\n", + " Connection 3 closed!\n", + " Connection 4 closed!\n", + " Connection 5 closed!\n", + " Connection 6 closed!\n", + " Connection 7 closed!\n", + " Connection 8 closed!\n", + " Connection 9 closed!\n", + " Connection 10 closed!\n", + "\n", + "All Db2 server connections have been returned the pool of connections opened earlier.\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-pconnect_SERVER.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.pconnect() API to #\n", + "# create a pool of connections to a remote Db2 server. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.createdbNX() #\n", + "# ibm_db.close() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "hostName = \"197.126.80.22\" # IP Address Of Remote Server\n", + "portNum = \"50000\" # Port Number That Receives Db2 Connections On The Remote Server \n", + "userID = \"db2inst2\" # The Instance User ID At The Remote Server\n", + "passWord = \"ibmdb2\" # The Password For The Instance User ID At The Remote Server\n", + "svrConnection = list(range(10))\n", + "dbName = \"MY_DB\"\n", + "returnCode = None\n", + "\n", + "# Construct The String That Will Be Used To Establish A Db2 Server Connection\n", + "connString = \"DRIVER={IBM DB2 ODBC DRIVER}\"\n", + "connString += \";ATTACH=TRUE\" # Attach To A Server; Not A Database\n", + "connString += \";DATABASE=\" # Ignored When Connecting To A Server\n", + "connString += \";HOSTNAME=\" + hostName # Required To Connect To A Server\n", + "connString += \";PORT=\" + portNum # Required To Connect To A Server\n", + "connString += \";PROTOCOL=TCPIP\" # Required To Connect To A Server\n", + "connString += \";UID=\" + userID\n", + "connString += \";PWD=\" + passWord\n", + "\n", + "# Display A Status Message Indicating An Attempt To Establish Ten Connections To A Remote \n", + "# Db2 Server Is About To Be Made\n", + "print(\"\\nEstablishing 10 connections to the \\'\" + hostName + \"\\' server ... \\n\")\n", + "\n", + "# Establish Ten Connections To The Db2 Server Specified\n", + "for loopCounter in range(10):\n", + "\n", + " # Attempt To Establish A Db2 Server Connection \n", + " try:\n", + " svrConnection[loopCounter] = ibm_db.pconnect(connString, '', '')\n", + " except Exception:\n", + " pass\n", + "\n", + " # If A Connection Could Not Be Established, Display An Error Message And Continue\n", + " if svrConnection[loopCounter] is None:\n", + " print(\"\\nERROR: Unable to connect to the \\'\" + hostName + \"\\' server.\")\n", + " continue\n", + "\n", + " # Otherwise, Display A \"Connection Ready\" Status Message\n", + " else:\n", + " print(\" Connection {:>2} ready!\" .format(loopCounter + 1))\n", + "\n", + "# Add A Blank Line To The End Of The List Of Connections Created\n", + "print()\n", + "\n", + "# Attempt To Create A New Database At The Remote Server Using Connection Number Five\n", + "if not svrConnection[5] is None:\n", + " print(\"Creating a database named \" + dbName + \" using Connection 5. Please wait.\")\n", + " try:\n", + " returnCode = ibm_db.createdbNX(svrConnection[5], dbName)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Database Could Not Be Created, Display An Error Message And Exit \n", + " if returnCode is None:\n", + " print(\"ERROR: Unable to create the \" + dbName + \" database.\\n\")\n", + " errorMsg = ibm_db.conn_errormsg(svrConnection[5])\n", + " print(errorMsg + \"\\n\")\n", + "\n", + " # Otherwise, Display A Status Message Indicating The Database Was Created \n", + " else:\n", + " print(\"\\nThe database \\\"\" + dbName + \"\\\" has been created!\\n\")\n", + "\n", + " # Attempt To Close The Db2 Server Connection (Connection 5)\n", + " print(\"Closing Db2 server Connection 5 ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.close(svrConnection[5])\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Connection Was Not Closed, Display An Error Message\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + hostName + \" server.\")\n", + " \n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\")\n", + " print(\"(Connection 5 has been returned the pool of connections opened earlier.)\\n\")\n", + "\n", + "# Display A Status Message Indicating An Attempt To Close The Remaining Db2 Server\n", + "# Connections Is About To Be Made\n", + "print(\"Closing all remaining connections to the \\'\" + hostName + \"\\' server ... \\n\")\n", + "\n", + "# Attempt To Close All Of The Remaining Db2 Server Connections That Were Opened Earlier\n", + "for loopCounter in range(10):\n", + " \n", + " # If The Specified Connection Is Open, Attempt To Close It\n", + " if not svrConnection[loopCounter] is None:\n", + " try:\n", + " returnCode = ibm_db.close(svrConnection[loopCounter])\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Connection Could Not Be Closed, Display An Error Message And Continue\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + hostName + \" server.\")\n", + " continue\n", + "\n", + " # Otherwise, Display A \"Connection Closed\" Status Message\n", + " else:\n", + " print(\" Connection {:>2} closed!\" .format(loopCounter + 1))\n", + "\n", + "# Display A Status Message Indicating All Db2 Server Connections Have Been Returned To The\n", + "# Connection Pool\n", + "print(\"\\nAll Db2 server connections have been returned the pool of connections opened earlier.\\n\")\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-prepare.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-prepare.ipynb new file mode 100644 index 0000000..506d1ff --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-prepare.ipynb @@ -0,0 +1,332 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.prepare()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Send an SQL statement to a Db2 server or database to have it prepared for execution." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.prepare( IBM_DBConnection `*`connection,`*` string `*`SQLstatement`*` [, dictionary `*`options`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__        : A valid Db2 server or database connection.\n", + "* __*SQLstatement*__   : A valid, executable SQL statement (that may or may not contain one or more parameter markers).\n", + "* __options__              : A dictionary containing key-value pairs for the statement attributes that are to be set when the statement provided in the __*SQLstatement*__ parameter is prepared. Valid keys and values are:

\n", + " \n", + " * `ibm_db.SQL_ATTR_CURSOR_TYPE`                             : Specifies the type of cursor that is to be used for processing result sets. Valid values are:\n", + " * `ibm_db.SQL_CURSOR_FORWARD_ONLY`                 : A forward only cursor should be used (i.e., a cursor that only scrolls forward).\n", + " * `ibm_db. SQL_CURSOR_KEYSET_DRIVEN`             : A keyset-driven cursor should be used.\n", + " * `ibm_db.SQL_CURSOR_STATIC`                             : A static cursor should be used.\n", + " * `ibm_db.SQL_CURSOR_DYNAMIC`                           : A dynamic, scrollable cursor that detects all changes to the result set, should be used. Dynamic cursors are only supported by Db2 for z/OS servers.\n", + " * `ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH`                 : Enables Db2 to determine the number of rows that are returned by a query (so the entire result set can be prefetched into memory, when possible); `ibm_db.SQL_ROWCOUNT_PREFETCH_ON` will turn this behavior __ON__ and `ibm_db.SQL_ROWCOUNT_PREFETCH_OFF` will turn it __OFF__.\n", + " * `ibm_db.SQL_ATTR_QUERY_TIMEOUT`                         : The number of seconds to wait for an SQL statement to execute before aborting and returning to the application. This option can be used to terminate long running queries — the default value of __0__ means an application will wait indefinitely for the server to complete execution.

" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, a valid `IBM_DBStatement` object.\n", + "* If __unsuccessful__, the value `None`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.prepare()__ API is used to send an SQL statement to a Db2 server or database to have it prepared for execution — once an SQL statement has been prepared, it can be submitted for execution multiple times without having to be re-prepared. This benefits applications in two ways:

\n", + "\n", + "* __Improved performance__: when an SQL statement is prepared, the database server creates an optimized access plan for executing that statement. Subsequent executions of the prepared statement (using the __ibm_db.execute()__ or __ibm_db.execute_many()__ API) will reuse that access plan, eliminating the overhead of dynamically creating new access plans each time the statement is executed.

\n", + " \n", + "* __Greater flexibility__: when an SQL statement is prepared, literal values hard-coded in the statement can be replaced with parameter markers — depicted by question mark (?) characters. An SQL statement can contain zero or more parameter markers, each representing a variable or value that is to be provided at run time. Values for parameter markers can be supplied via variables (using the __ibm_db.bind_param()__ API), or for input parameters only, in a tuple (if the __ibm_db.execute()__ API is used) or a tuple of tuples (if the __ibm_db.execute_many()__ API is used). Regardless of which method used, when the prepared statement is executed, the database server will check each input value supplied to ensure the appropriate data type is used.

\n", + " \n", + "It is important to note that parameter markers are only allowed in certain places in an SQL statement. For example, they cannot be used to represent one or more columns in the result set reurned by a __SELECT__ statement, nor can they be used as the operand of a binary operator like the equal sign (=)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Preparing the SQL statement \"SELECT lastname, firstnme FROM employee WHERE job = 'PRES'\" ... Done!\n", + "\n", + "Executing the prepared SQL statement ... Done!\n", + "\n", + "Query results:\n", + "\n", + "FIRSTNME LASTNAME\n", + "__________ ________\n", + "CHRISTINE HAAS \n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-prepare.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.prepare() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.execute() #\n", + "# ibm_db.fetch_assoc() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "preparedStmt = False\n", + "returnCode = False\n", + "dataRecord = None\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT lastname, firstnme FROM employee WHERE job = 'PRES'\"\n", + "\n", + "# Prepare The SQL Statement Just Defined\n", + "print(\"Preparing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit\n", + "if preparedStmt is False:\n", + " print(\"\\nERROR: Unable to prepare the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Execute The SQL Statement Just Prepared\n", + "print(\"Executing the prepared SQL statement ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.execute(preparedStmt)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Retrieve The Data Produced By The SQL Statement And Store It In A Python Dictionary\n", + "try:\n", + " dataRecord = ibm_db.fetch_assoc(preparedStmt)\n", + "except:\n", + " pass\n", + "\n", + "# If The Data Could Not Be Retrieved, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to retrieve the data produced by the SQL statement.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# If The Data Could be Retrieved, Display It\n", + "else:\n", + " print(\"Query results:\\n\")\n", + " print(\"FIRSTNME LASTNAME\")\n", + " print(\"__________ ________\")\n", + " print(\"{:10} {:<24}\\n\" .format(dataRecord['FIRSTNME'], dataRecord['LASTNAME']))\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-primary_keys.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-primary_keys.ipynb new file mode 100644 index 0000000..f9895fe --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-primary_keys.ipynb @@ -0,0 +1,328 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.primary_keys()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve information about the columns that make up the primary key for a table." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.primary_keys( IBM_DBConnection `*`connection,`*` string `*`qualifierName,`*` string `*`schemaName,`*` string `*`tableName`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__        : A valid Db2 server or database connection. \n", + "* __qualifierName__    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value `None` or an empty string (`''`) for Db2 databases on other operating systems. \n", + "* __schemaName__     : The name of the schema that contains the table(s) that primary key information is to be obtained for. To use the schema associated with the current connection, provide the value `None`.\n", + "* __tableName__          : The name of the table(s) that primary key information is to be obtained for. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an IBM_DBStatement with a result set that contains the following information:

\n", + "\n", + " * `PK_NAME`            : The name of the primary key.\n", + " * `TABLE_CAT`        : The name of the catalog associated with the schema and table that contains the primary key; Db2 does not use catalogs so this field will always contain the value `None`. *(Db2 databases on OS/390 or z/OS servers can return information in this field.)*\n", + " * `TABLE_SCHEM`    : The name of the schema for the table that contains the primary key.\n", + " * `TABLE_NAME`      : The name of the table that contains the primary key.\n", + " * `COLUMN_NAME`    : The name of a primary key column.\n", + " * `KEY_SEQ`            : The __COLUMN_NAME__ column's ordinal position in the primary key, starting from 1.\n", + "

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.primary_keys()__ API is used to retrieve information about the columns that make up the primary key for a table (if one has been defined).

\n", + "\n", + "The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Obtaining information about primary keys created for the DB2INST1.PROJECT table ... Done!\n", + "\n", + "Primary key 1 details:\n", + "______________________________________\n", + "Primary key table schema : DB2INST1\n", + "Primary key table name : PROJECT\n", + "Primary key column name : PROJNO\n", + "Primary key column number : 1\n", + "Primary key name : PK_PROJECT\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-primary_keys.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.primary_keys() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.fetch_assoc() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "schemaName = userID.upper()\n", + "tableName = \"PROJECT\"\n", + "resultSet = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Retrieve Information About All Primary Keys That Have Been Defined For The\n", + "# Table Specified\n", + "print(\"Obtaining information about primary keys created for \", end=\"\")\n", + "print(\"the \" + schemaName + \".\" + tableName + \" table ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.primary_keys(dbConnection, None, schemaName, tableName)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit\n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired\\n.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# As Long As There Are Records (That Were Produced By The ibm_db.primary_keys API), ...\n", + "noData = False\n", + "loopCounter = 1\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Information Retrieved\n", + " else:\n", + "\n", + " # Display Record Header Information\n", + " print(\"Primary key \" + str(loopCounter) + \" details:\")\n", + " print(\"______________________________________\")\n", + "\n", + " # Display The Information Stored In The Data Record Retrieved\n", + " print(\"Primary key table schema : {}\" .format(dataRecord['TABLE_SCHEM']))\n", + " print(\"Primary key table name : {}\" .format(dataRecord['TABLE_NAME']))\n", + " print(\"Primary key column name : {}\" .format(dataRecord['COLUMN_NAME']))\n", + " print(\"Primary key column number : {}\" .format(dataRecord['KEY_SEQ']))\n", + " print(\"Primary key name : {}\" .format(dataRecord['PK_NAME']))\n", + "\n", + " # Increment The loopCounter Variable And Print A Blank Line To Separate The\n", + " # Records From Each Other\n", + " loopCounter += 1\n", + " print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-procedure_columns.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-procedure_columns.ipynb new file mode 100644 index 0000000..d6209e1 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-procedure_columns.ipynb @@ -0,0 +1,444 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.procedure_columns()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Pupose:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Retrieve information about the parameters that have been defined for one or more procedures." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.procedure_columns( IBM_DBConnection `*`connection,`*
` string `*`qualifierName,`*` string `*`schemaName,`*` string `*`procedureName,`*` string `*`parameterName`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* __*connection*__          : A valid Db2 server or database connection. \n", + "* __qualifierName__      : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value `None` or an empty string (`''`) for Db2 databases on other operating systems. \n", + "* __schemaName__       : The name of the schema that contains the procedure(s) that parameter information is to be obtained for. To match all schemas, provide the value `None` or an empty string; to match select schemas, provide a search pattern that contains __`_`__ and/or __`%`__ wildcards.\n", + "* __procedureName__   : The name of the procedure(s) that parameter information is to be obtained for. To match all procedures, provide the value `None` or an empty string; to match select procedures, provide a search pattern that contains __`_`__ and/or __`%`__ wildcards.\n", + "* __parameterName__    : The name of the parameter(s) that information is to be obtained for. To match all parameters, provide the value `None` or an empty string; to match select parameters, provide a search pattern that contains __`_`__ and/or __`%`__ wildcards. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an IBM_DBStatement with a result set that contains the following information:

\n", + "\n", + " * `PROCEDURE_CAT`            : The name of the catalog associated with the schema that contains the procedure; Db2 does not use catalogs so this field will always contain the value `None`. *(Db2 databases on OS/390 or z/OS servers can return information in this field.)*\n", + " * `PROCEDURE_SCHEM`        : The name of the schema that contains the procedure.\n", + " * `PROCEDURE_NAME`          : The name of the procedure.\n", + " * `COLUMN_NAME`                : The name of a parameter that has been defined for the procedure.\n", + " * `COLUMN_TYPE`                : A value that indicates what type of parameter the parameter is. Valid values for this field are:

\n", + " \n", + " * `ibm_db.SQL_PARAM_INPUT`                 : The parameter is an input (IN) parameter.\n", + " * `ibm_db.SQL_PARAM_OUTPUT`               : The parameter is an output (OUT) parameter.\n", + " * `ibm_db.SQL_PARAM_INPUT_OUTPUT`   : The parameter is an input/output (INOUT) parameter.

\n", + " \n", + " * `DATA_TYPE`                    : An integer value that represents the SQL data type of the parameter. On Linux and UNIX systems, valid values for this field can be found in the file */opt/ibm/db2/V11.1/include/sqlcli.h*.\n", + " * `TYPE_NAME`                    : The data source-specific string representation of the SQL data type of the parameter.\n", + " * `COLUMN_SIZE`                : The maximum number of bytes needed to display the parameter's data as a string.\n", + " * `BUFFER_LENGTH`            : The maximum number of bytes needed to store the parameter's data in an application variable.\n", + " * `DECIMAL_DIGITS`          : The scale (i.e., total number of significant digits to the right of the decimal point) of the parameter - provided the parameter has a numerical data type. If the parameter does not have a numerical data type, this field will contain the value `None`.\n", + " * `NUM_PREC_RADIX`          : A numerical value that indicates whether the parameter's data type represents an exact numeric data type (`10`) or an approximate numeric data type (`2`). If the parameter does not have a numerical data type, this field will contain the value `None`.\n", + " * `NULLABLE`                      : Indication of whether the parameter accepts a __NULL__ value; `ibm_db.SQL_YES` will be returned if __NULL__ values are accepted and `ibm_db.SQL_NO` will be returned if they are not..\n", + " * `REMARKS`                        : A user-supplied description of the parameter (if one has been provided).\n", + " * `COLUMN_DEF`                  : The default value for the parameter (if one has been defined).\n", + " * `SQL_DATA_TYPE`            : An integer value that represents the SQL data type of the parameter, as it would appear in a row descriptor record. On Linux and UNIX systems, valid values for this field can be found in the file */opt/ibm/db2/V11.1/include/sqlcli.h*. (In most cases, this will be the same as the value provided in the __DATA_TYPE__ field.)\n", + " * `SQL_DATETIME_SUB`      : An integer value that represents the SQL date/time subtype code for the parameter - provided the parameter has a date, time, or timestamp data type. If the parameter does not have one of these data types, this field will contain the value `None`. (On Linux and UNIX systems, valid values for this field can be found in the file */opt/ibm/db2/V11.1/include/sqlcli.h*.)\n", + " * `CHAR_OCTET_LENGTH`    : The maximum length, in octets (8-bit bytes), needed to display the parameter's data as a string. (This will be the same as the __COLUMN_SIZE__ value for single-byte character set data.) If the parameter does not have a character data type, this field will contain the value `None`.\n", + " * `ORDINAL_POSITION`      : The parameter's ordinal position in the __CALL__ statement that would be used to invoke the procedure, starting from 1.\n", + " * `IS_NULLABLE`                : Indication of whether the parameter can contain __NULL__ values, according to the rules in the ISO SQL92 standard. This field will contain the value `\"YES\"` if the column can contain __NULL__ values and the value `\"NO\"` if it cannot.

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.procedure_columns()__ API is used to retrieve information about the parameters that have been defined for one or more stored procedures.\n", + "\n", + "The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Obtaining information about the parameters that have been defined for the VALIDATE_LENGTH\n", + "procedure ... Done!\n", + "\n", + "Stored procedure parameter 1 details:\n", + "____________________________________________________________\n", + "Procedure schema : SYSIBMADM\n", + "Procedure name : VALIDATE_LENGTH\n", + "Parameter name : LENGTH1\n", + "Parameter type : Input (IN)\n", + "Data type : INTEGER\n", + "Size : 10\n", + "Buffer size : 4\n", + "Scale (decimal digits) : 0\n", + "Precision radix : Exact numeric data type\n", + "Can accept NULL values : YES\n", + "Remarks : None\n", + "Default value : None\n", + "SQL data type : SQL_INTEGER\n", + "SQL data/time subtype : None\n", + "Length in octets : Not applicable\n", + "Ordinal position : 1\n", + "Can accept or return 'None' values : YES\n", + "\n", + "Stored procedure parameter 2 details:\n", + "____________________________________________________________\n", + "Procedure schema : SYSIBMADM\n", + "Procedure name : VALIDATE_LENGTH\n", + "Parameter name : LENGTH2\n", + "Parameter type : Input (IN)\n", + "Data type : INTEGER\n", + "Size : 10\n", + "Buffer size : 4\n", + "Scale (decimal digits) : 0\n", + "Precision radix : Exact numeric data type\n", + "Can accept NULL values : YES\n", + "Remarks : None\n", + "Default value : None\n", + "SQL data type : SQL_INTEGER\n", + "SQL data/time subtype : None\n", + "Length in octets : Not applicable\n", + "Ordinal position : 2\n", + "Can accept or return 'None' values : YES\n", + "\n", + "Stored procedure parameter 3 details:\n", + "____________________________________________________________\n", + "Procedure schema : SYSIBMADM\n", + "Procedure name : VALIDATE_LENGTH\n", + "Parameter name : ERRORCODE\n", + "Parameter type : Input (IN)\n", + "Data type : VARCHAR\n", + "Size : 10\n", + "Buffer size : 10\n", + "Scale (decimal digits) : Not applicable\n", + "Precision radix : Not applicable\n", + "Can accept NULL values : YES\n", + "Remarks : None\n", + "Default value : None\n", + "SQL data type : SQL_VARCHAR\n", + "SQL data/time subtype : None\n", + "Length in octets : 10\n", + "Ordinal position : 3\n", + "Can accept or return 'None' values : YES\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-procedure_columns.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.procedure_columns() #\n", + "# API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.fetch_assoc() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "procedureName = 'VALIDATE_LENGTH'\n", + "resultSet = False\n", + "dataRecord = False\n", + "sqlDataTypes = {0 : \"SQL_UNKNOWN_TYPE\", 1 : \"SQL_CHAR\", 2 : \"SQL_NUMERIC\", 3 : \"SQL_DECIMAL\",\n", + " 4 : \"SQL_INTEGER\", 5 : \"SQL_SMALLINT\", 6 : \"SQL_FLOAT\", 7 : \"SQL_REAL\", 8 : \"SQL_DOUBLE\",\n", + " 9 : \"SQL_DATETIME\", 12 : \"SQL_VARCHAR\", 16 : \"SQL_BOOLEAN\", 19 : \"SQL_ROW\", \n", + " 91 : \"SQL_TYPE_DATE\", 92 : \"SQL_TYPE_TIME\", 93 : \"SQL_TYPE_TIMESTAMP\",\n", + " 95 : \"SQL_TYPE_TIMESTAMP_WITH_TIMEZONE\", -8 : \"SQL_WCHAR\", -9 : \"SQL_WVARCHAR\",\n", + " -10 : \"SQL_WLONGVARCHAR\", -95 : \"SQL_GRAPHIC\", -96 : \"SQL_VARGRAPHIC\",\n", + " -97 : \"SQL_LONGVARGRAPHIC\", -98 : \"SQL_BLOB\", -99 : \"SQL_CLOB\", -350 : \"SQL_DBCLOB\",\n", + " -360 : \"SQL_DECFLOAT\", -370 : \"SQL_XML\", -380 : \"SQL_CURSORHANDLE\", -400 : \"SQL_DATALINK\",\n", + " -450 : \"SQL_USER_DEFINED_TYPE\"}\n", + "sqlDateTimeSubtypes = {1 : \"SQL_CODE_DATE\", 2 : \"SQL_CODE_TIME\", 3 : \"SQL_CODE_TIMESTAMP\",\n", + " 4 : \"SQL_CODE_TIMESTAMP_WITH_TIMEZONE\"}\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Retrieve Information About The Parameters That Have Been Defined For A Particular\n", + "# Stored Procedure\n", + "print(\"Obtaining information about the parameters that have been defined for the \", end=\"\")\n", + "print(procedureName + \"\\nprocedure ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.procedure_columns(dbConnection, None, '', procedureName, None)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit\n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired\\n.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# As Long As There Are Records (That Were Produced By The ibm_db.procedure_columns API), ...\n", + "noData = False\n", + "loopCounter = 1\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Information Retrieved\n", + " else:\n", + "\n", + " # Display Record Header Information\n", + " print(\"Stored procedure parameter \" + str(loopCounter) + \" details:\")\n", + " print(\"____________________________________________________________\")\n", + "\n", + " # Display The Information Stored In The Data Record Retrieved\n", + " print(\"Procedure schema : {}\" .format(dataRecord['PROCEDURE_SCHEM']))\n", + " print(\"Procedure name : {}\" .format(dataRecord['PROCEDURE_NAME']))\n", + " print(\"Parameter name : {}\" .format(dataRecord['COLUMN_NAME']))\n", + " print(\"Parameter type : \", end=\"\")\n", + " if dataRecord['COLUMN_TYPE'] == ibm_db.SQL_PARAM_INPUT:\n", + " print(\"Input (IN)\")\n", + " elif dataRecord['COLUMN_TYPE'] == ibm_db.SQL_PARAM_INPUT_OUTPUT:\n", + " print(\"Input/output (INOUT)\")\n", + " elif dataRecord['COLUMN_TYPE'] == ibm_db.SQL_PARAM_OUTPUT:\n", + " print(\"Output (OUT)\")\n", + " else:\n", + " print(\"Unknown\")\n", + " print(\"Data type : {}\" .format(dataRecord['TYPE_NAME']))\n", + " print(\"Size : {}\" .format(dataRecord['COLUMN_SIZE']))\n", + " print(\"Buffer size : {}\" .format(dataRecord['BUFFER_LENGTH']))\n", + " print(\"Scale (decimal digits) : \", end=\"\")\n", + " if dataRecord['DECIMAL_DIGITS'] == None:\n", + " print(\"Not applicable\")\n", + " else:\n", + " print(\"{}\" .format(dataRecord['DECIMAL_DIGITS']))\n", + " print(\"Precision radix : \", end=\"\")\n", + " if dataRecord['NUM_PREC_RADIX'] == 10:\n", + " print(\"Exact numeric data type\")\n", + " elif dataRecord['NUM_PREC_RADIX'] == 2:\n", + " print(\"Approximate numeric data type\")\n", + " elif dataRecord['NUM_PREC_RADIX'] == None:\n", + " print(\"Not applicable\")\n", + " print(\"Can accept NULL values : \", end=\"\")\n", + " if dataRecord['NULLABLE'] == 1:\n", + " print(\"YES\")\n", + " else:\n", + " print(\"NO\")\n", + " print(\"Remarks : {}\" .format(dataRecord['REMARKS']))\n", + " print(\"Default value : {}\" .format(dataRecord['COLUMN_DEF']))\n", + " print(\"SQL data type : \", end=\"\")\n", + " print(sqlDataTypes.get(dataRecord['SQL_DATA_TYPE']))\n", + " print(\"SQL data/time subtype : \", end=\"\")\n", + " print(sqlDateTimeSubtypes.get(dataRecord['SQL_DATETIME_SUB']))\n", + " print(\"Length in octets : \", end=\"\")\n", + " if dataRecord['CHAR_OCTET_LENGTH'] == None:\n", + " print(\"Not applicable\")\n", + " else:\n", + " print(\"{}\" .format(dataRecord['CHAR_OCTET_LENGTH']))\n", + " print(\"Ordinal position : {}\" .format(dataRecord['ORDINAL_POSITION']))\n", + " print(\"Can accept or return \\'None\\' values : {}\" .format(dataRecord['IS_NULLABLE']))\n", + "\n", + " # Increment The loopCounter Variable And Print A Blank Line To Separate The\n", + " # Records From Each Other\n", + " loopCounter += 1\n", + " print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-procedures.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-procedures.ipynb new file mode 100644 index 0000000..5eed548 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-procedures.ipynb @@ -0,0 +1,348 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.procedures()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve a list of procedures that have been registered in a database." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.procedures( IBM_DBConnection `*`connection,`*` string `*`qualifierName,`*` string `*`schemaName,`*` string `*`procedureName`*` )` " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__          : A valid Db2 server or database connection. \n", + "* __qualifierName__      : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value `None` or an empty string (`''`) for Db2 databases on other operating systems. \n", + "* __schemaName__       : The name of the schema that contains the procedure(s) that information is to be obtained for. To match all schemas, provide the value `None` or an empty string; to match select schemas, provide a search pattern that contains __`_`__ and/or __`%`__ wildcards.\n", + "* __procedureName__   : The name of the procedure(s) that information is to be obtained for. To match all procedures, provide the value `None` or an empty string; to match select procedures, provide a search pattern that contains __`_`__ and/or __`%`__ wildcards. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an IBM_DBStatement with a result set that contains the following information:

\n", + "\n", + " * `PROCEDURE_CAT`          : The name of the catalog associated with the schema that contains the procedure; Db2 does not use catalogs so this field will always contain the value `None`. *(Db2 databases on OS/390 or z/OS servers can return information in this field.)*\n", + " * `PROCEDURE_SCHEM`      : The name of the schema that contains the procedure.\n", + " * `PROCEDURE_NAME`        : The name of the procedure.\n", + " * `NUM_INPUT_PARAMS`    : The number of input (IN) parameters that have been defined for the procedure.\n", + " * `NUM_OUTPUT_PARAMS`  : The number of output (OUT) parameters that have been defined for the procedure.\n", + " * `NUM_RESULT_SETS`      : The number of result sets the procedure will return.\n", + " * `REMARKS`                      : A user-supplied description of the procedure (if one has been provided).\n", + " * `PROCEDURE_TYPE`        : A numerical value that indicates whether the procedure is a stored procedure that does not return a value (`1`) or a function that returns a value (`2`). This field will always contain the value `1`.

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.procedures()__ API is used to retrieve a list of stored procedures that have been registered in a database.

\n", + "\n", + "The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Obtaining information about stored procedures in the DB2INST1 schema ... Done!\n", + "\n", + "Stored procedure 1 details:\n", + "_______________________________________________\n", + "Procedure schema : DB2INST1\n", + "Procedure name : BONUS_INCREASE\n", + "Number of input parameters : 0\n", + "Number of output parameters : 0\n", + "Number of result sets produced : 1\n", + "Procedure comments : None\n", + "\n", + "Stored procedure 2 details:\n", + "_______________________________________________\n", + "Procedure schema : DB2INST1\n", + "Procedure name : HIGH_EARNERS\n", + "Number of input parameters : 0\n", + "Number of output parameters : 0\n", + "Number of result sets produced : 3\n", + "Procedure comments : None\n", + "\n", + "Stored procedure 3 details:\n", + "_______________________________________________\n", + "Procedure schema : DB2INST1\n", + "Procedure name : SALARY_STATS\n", + "Number of input parameters : 0\n", + "Number of output parameters : 0\n", + "Number of result sets produced : 0\n", + "Procedure comments : None\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-procedures.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.procedures() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.fetch_assoc() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "schemaName = userID.upper()\n", + "resultSet = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Retrieve Information About Stored Procedures That Have Been Defined In The\n", + "# Current User's Schema\n", + "print(\"Obtaining information about stored procedures in the \", end=\"\")\n", + "print(schemaName + \" schema ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.procedures(dbConnection, None, schemaName, '')\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit\n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired\\n.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# As Long As There Are Records (That Were Produced By The ibm_db.procedures API), ...\n", + "noData = False\n", + "loopCounter = 1\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + " \n", + " # Otherwise, Display The Information Retrieved\n", + " else:\n", + "\n", + " # Display Record Header Information\n", + " print(\"Stored procedure \" + str(loopCounter) + \" details:\")\n", + " print(\"_______________________________________________\")\n", + "\n", + " # Display The Information Stored In The Data Record Retrieved\n", + " print(\"Procedure schema : {}\" .format(dataRecord['PROCEDURE_SCHEM']))\n", + " print(\"Procedure name : {}\" .format(dataRecord['PROCEDURE_NAME']))\n", + " print(\"Number of input parameters : {}\" .format(dataRecord['NUM_INPUT_PARAMS']))\n", + " print(\"Number of output parameters : {}\" .format(dataRecord['NUM_OUTPUT_PARAMS']))\n", + " print(\"Number of result sets produced : {}\" .format(dataRecord['NUM_RESULT_SETS']))\n", + " print(\"Procedure comments : {}\" .format(dataRecord['REMARKS']))\n", + "\n", + " # Increment The loopCounter Variable And Print A Blank Line To Separate The\n", + " # Records From Each Other\n", + " loopCounter += 1\n", + " print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-recreatedb.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-recreatedb.ipynb new file mode 100644 index 0000000..fd6f6a9 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-recreatedb.ipynb @@ -0,0 +1,415 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.recreatedb()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Drop and recreate a database, using the name and code set specified." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.recreatedb( IBM_DBConnection `*`connection,`*` string `*`dbName`*` [, string `*`codeSet`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server connection. \n", + "* __*dbName*__         : The name of the database that is to be dropped and recreated. \n", + "* __*codeSet*__         : The code set that is to be used for storing data that is entered into the database *after it has been dropped and recreated*. If a __*codeSet*__ value is not specified, the UTF-8 (Unicode) code set is used." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return Value:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : The database specified was dropped and recreated. \n", + "* `False`    : The database specified could not be dropped and recreated." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.recreatedb()__ API is used to delete (drop) an existing database, and then recreate it; the code set that is to be used for storing data entered into the database can also be changed when this API is executed. (The *code set* controls how unique numbers are assigned to characters in a particular character set.)

" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Examples:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 1: Drop and recreate a database stored on a local server" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the local server ... Done!\n", + "\n", + "Dropping and recreating a database named MY_DB. Please wait.\n", + "\n", + "The database \"MY_DB\" has been created!\n", + "\n", + "Disconnecting from the local server ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-recreatedb_LOCAL.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.recreatedb() API to #\n", + "# drop and recreate a local Db2 database. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.conn_errormsg() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "userID = \"db2inst1\" # User ID (Recognized By The Local Server)\n", + "passWord = \"Passw0rd\" # User Password\n", + "svrConnection = None\n", + "dbName = \"MY_DB\"\n", + "returnCode = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To The Local Db2 Server\n", + "conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " svrConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Drop And Recreate A Database At The Local Server\n", + "print(\"Dropping and recreating a database named \" + dbName + \". Please wait.\")\n", + "try:\n", + " returnCode = ibm_db.recreatedb(svrConnection, dbName, 'UTF-8')\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Database Could Not Be Recreated, Display An Error Message And Exit \n", + "if returnCode is None:\n", + " print(\"ERROR: Unable to drop and recreate the \" + dbName + \" database.\\n\")\n", + " errorMsg = ibm_db.conn_errormsg(svrConnection)\n", + " print(errorMsg + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + " \n", + "# Otherwise, Display A Status Message \n", + "else:\n", + " print(\"\\nThe database \\\"\" + dbName + \"\\\" has been created!\\n\")\n", + " # query_sdb_dir(dbName)\n", + "\n", + "# Close The Db2 Server Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###   Example 2: Drop and recreate a database stored on a remote server" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the 197.126.80.22 server ... Done!\n", + "\n", + "Dropping and recreating a database named MY_DB at the 197.126.80.22 server. Please wait.\n", + "\n", + "The database \"MY_DB\" has been recreated!\n", + "\n", + "Disconnecting from the 197.126.80.22 server ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-recreatedb_REMOTE.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.recreatedb() API to #\n", + "# drop and recreate a database on a remote Db2 server. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.conn_errormsg() #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "hostName = \"197.126.80.22\" # IP Address Of A Remote Server\n", + "portNum = \"50000\" # Port Number Used By Db2\n", + "userID = \"db2inst2\" # User ID (Recognized By The Remote Server)\n", + "passWord = \"ibmdb2\" # User Password\n", + "svrConnection = None\n", + "dbName = \"MY_DB\"\n", + "returnCode = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Remote Db2 Server\n", + "conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " svrConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Delete (Drop) And Recreate A Database At The Remote Server\n", + "print(\"Dropping and recreating a database named \" + dbName + \" \", end=\"\")\n", + "print(\"at the \" + hostName + \" server. Please wait.\")\n", + "try:\n", + " returnCode = ibm_db.recreatedb(svrConnection, dbName, 'UTF-8')\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Database Could Not Be Recreated, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to drop and recreate the \" + dbName + \" database.\\n\")\n", + " errorMsg = ibm_db.conn_errormsg(svrConnection)\n", + " print(errorMsg + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Display A Status Message And Verify That Information About The Database\n", + "# That Was Just Recreated Exists In The Db2 System Database Directory\n", + "else:\n", + " print(\"\\nThe database \\\"\" + dbName + \"\\\" has been recreated!\\n\")\n", + "\n", + "# Close The Db2 Server Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-result.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-result.ipynb new file mode 100644 index 0000000..fa64fc8 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-result.ipynb @@ -0,0 +1,296 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.result()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose: " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve a value from a column in the current row of a result set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`mixed ibm_db.result( IBM_DBStatement `*`statement,`*` mixed `*`column`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object that contains a result set. \n", + "* __column__        : The zero-indexed position of the column *or* the name of the column in the result set that data is to be retrieved from. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, the value for the column specified, *in the current row* of the result set.\n", + "* If __unsuccessful__ or if the column specified doesn't exist, the value `None`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false + }, + "source": [ + "The __ibm_db.result()__ API is used to retrieve a value from a column in the current row of a result set. This function is used in conjunction with the __ibm_db.fetch_row()__ API, which is used to advance a cursor to the next row *or* move a cursor to a specific row in a result set. Once the cursor has been moved, this API is then called to retrieve data for individual columns in the row.

\n", + " \n", + "As an alternative to using the __ibm_db.fetch_row()__ and __ibm_db.result()__ APIs to iterate through a result set and retrieve data values for individual columns, applications can use the __ibm_db.fetch_tuple()__, __ibm_db.fetch_assoc()__, or __ibm_db.fetch_both()__ API to position the cursor in a result set and retrieve the data for a complete row, in a single operation." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement \"SELECT deptname FROM department WHERE admrdept = 'A00'\" ... Done!\n", + "\n", + "Query results:\n", + "\n", + "DEPTNAME\n", + "____________________________\n", + "SPIFFY COMPUTER SERVICE DIV.\n", + "PLANNING\n", + "INFORMATION CENTER\n", + "DEVELOPMENT CENTER\n", + "SUPPORT SERVICES\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-result.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.fetch_row() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.fetch_row() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "resultSet = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT deptname FROM department WHERE admrdept = 'A00'\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Executing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Query results:\\n\")\n", + "print(\"DEPTNAME\")\n", + "print(\"____________________________\")\n", + "\n", + "# As Long As There Are Records In The Result Set Produced, ...\n", + "while (ibm_db.fetch_row(resultSet) is True):\n", + "\n", + " # Display The Data Retrieved\n", + " print(ibm_db.result(resultSet, 0)) \n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-rollback.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-rollback.ipynb new file mode 100644 index 0000000..62f8ee3 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-rollback.ipynb @@ -0,0 +1,344 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.rollback()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Terminate an in-progress transaction and back out (roll back) the effects of all operations performed by the transaction." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.rollback( IBM_DBConnection `*`connection`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server or database connection." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : Changes made by the current transaction were successfully backed out of the database (rolled back). \n", + "* `False`    : Changes made by the current transaction could not be rolled back." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.rollback()__ API is used to terminate an in-progress transaction and back out (roll back) the effects of all operations that were performed by that transaction. (A *transaction* is a sequence of one or more SQL operations that are grouped together as a single process; when a transaction is rolled back, the database is returned to the sate it was in at the time the transaction was started.) Normally, a transaction is initiated the first time an SQL statement is executed after a database connection is established or an in-progress transaction ends. But, with Python applications, each SQL operation is treated as a transaction that is implicitly committed (made permanent) as soon as it completes unless __AUTOCOMMIT__ behavior is turned __OFF__. Consequently, the __ibm_db.rollback()__ API has no effect when __AUTOCOMMIT__ behavior is __ON__ (the default).

\n", + "\n", + "It is important to note that if the connection being used is a persistent connection (i.e., a connection that was established with the __ibm_db.pconnect()__ API), in-progress transactions for *all applications using the connection will be rolled back when this API is called*. For this reason, the use of persistent connections is not recommended for applications that need to control transaction boundaries." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Turning AUTOCOMMIT behavior OFF ... Done!\n", + "\n", + "Number of records found in the DEPARTMENT table: 14\n", + "\n", + "Inserting a record into the DEPARTMENT table ... Done!\n", + "\n", + "Number of records found in the DEPARTMENT table: 15\n", + "\n", + "Backing out changes made to the database ... Done!\n", + "\n", + "Number of records found in the DEPARTMENT table: 14\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-rollback.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.rollback() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.autocommit() #\n", + "# ibm_db.exec_immediate() #\n", + "# ibm_db.stmt_errormsg() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The get_row_count() Function That Has Been Defined In The File Named #\n", + "# \"ibm_db_tools.py\"; This Function Contains The Programming Logic Needed To Obtain And #\n", + "# Display The Number Of Rows (Records) Found In A Db2 Database Table #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import get_row_count\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "returnCode = False\n", + "resultSet = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Turn Autocommit Behavior OFF\n", + "print(\"Turning AUTOCOMMIT behavior OFF ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_OFF)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If AUTOCOMMIT Behavior Could Not Be Turned OFF, Display An Error Message And Continue\n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to turn AUTOCOMMIT behavior OFF.\")\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table\n", + "returnCode = get_row_count(dbConnection, 'DEPARTMENT')\n", + "if returnCode is False:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The INSERT Statement That Is To Be Used To Add Data To The DEPARTMENT Table\n", + "sqlStatement = \"INSERT INTO department VALUES('K01', 'SALES', '000130', 'K01', NULL)\"\n", + "\n", + "# Execute The SQL Statement Just Defined\n", + "print(\"Inserting a record into the DEPARTMENT table ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the INSERT statement specified.\")\n", + " errorMsg = ibm_db.stmt_errormsg()\n", + " print(\"\\n\" + errorMsg + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display The Number Of Rows That Exist In The DEPARTMENT Table Now\n", + "# (The Number Returned Should Change)\n", + "returnCode = get_row_count(dbConnection, 'DEPARTMENT')\n", + "if returnCode is False:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Back Out The Changes Just Made To The Database\n", + "print(\"Backing out changes made to the database ... \", end=\"\")\n", + "resultSet = False\n", + "try:\n", + " resultSet = ibm_db.rollback(dbConnection)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Roll Back Operation Could Not Be Performed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to roll back the previous operation.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display The Number Of Rows That Exist In The DEPARTMENT Table Now\n", + "# (The Number Should Revert Back To The Original Value)\n", + "returnCode = get_row_count(dbConnection, 'DEPARTMENT')\n", + "if returnCode is False:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-server_info.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-server_info.ipynb new file mode 100644 index 0000000..04c9707 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-server_info.ipynb @@ -0,0 +1,466 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.server_info()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Obtain information about an IBM Db2 server." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`PyTypeObject ibm_db.server_info( IBM_DBConnection `*`connection`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__    : A valid Db2 server connection." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* If __successful__, a PyTypeObject populated with the following information:

\n", + "\n", + " * `DBMS_NAME`                         : The name of the Db2 server the application is connected to, in the form of a string that begins with the letters \"__DB2/__\" and is followed by the name of the operating system being used. For example, \"DB2/LINUXX8664\" indicates Db2 is running on a 64-bit Linux for x86 processor server. \n", + " * `DBMS_VER`                           : The version of the Db2 software running on the server, in the form of a string that has the format __VV.RR.MMFF__, where __VV__ is the major version, __RR__ is the release number, __MM__ is the modification number, and __FF__ is the fix pack number. For example, \"11.01.0404\" represents version 11, release 1, modification 4, fix pack 4.\n", + " * `DB_CODEPAGE`                     : The default code page that is used by the server.\n", + " * `DB_NAME`                             : The name of the database the application is connected to, if any.\n", + " * `DFT_ISOLATION`                 : The default transaction isolation level that is used by the server. Valid values are:

\n", + " \n", + " * `RR`     : Repeatable read. (Data affected by a pending transaction is not available to other transactions.)\n", + " * `RS`     : Read stability. (Concurrently running transactions can add or remove rows that do not match the search condition of a pending transaction.)\n", + " * `CS`     : Cursor stability. (Concurrently running transactions cannot update or delete the row a pending transaction currently holds.)\n", + " * `UR`     : Uncommitted read. (Changes made by concurrently running transactions are immediately visible.)\n", + " * `NC`     : No commit. (Changes are visible at the end of a successful operation; explicit commits and rollbacks are not allowed.)

\n", + "\n", + " * `IDENTIFIER_QUOTE_CHAR`  : The character that is used as an identifier delimiter.\n", + " * `INST_NAME`                           : The name of the Db2 instance at the server.\n", + " * `ISOLATION_OPTION`             : A list of the reansaction isolation levels that are supported by the connected server, stored in a tuple. Valid values are the same as those listed under `DFT_ISOLATION`.\n", + " * `KEYWORDS`                             : A list of the keywords that are reserved by the server, stored in a tuple.\n", + " * `LIKE_ESCAPE_CLAUSE`         : A boolean value indicating whether the database server supports the use of __%__ and __\\___ as wildcard characters (`True`) or not (`False`).\n", + " * `MAX_COL_NAME_LEN`             : Maximum length a column name can be, expressed in bytes.\n", + " * `MAX_IDENTIFIER_LEN`         : Maximum length an SQL identifier can be, expressed in characters.\n", + " * `MAX_INDEX_SIZE`                 : Maximum amount of data (from combined columns) that can be used in an index, expressed in bytes.\n", + " * `MAX_PROC_NAME_LEN`           : Maximum length a stored procedure name can be, expressed in bytes.\n", + " * `MAX_ROW_SIZE`                     : Maximum length a row in a base table can be, expressed in bytes.\n", + " * `MAX_SCHEMA_NAME_LEN`      : Maximum length a schema name can be, expressed in bytes.\n", + " * `MAX_STATEMENT_LEN`          : Maximum length an SQL statement can be, expressed in bytes.\n", + " * `MAX_TABLE_NAME_LEN`        : Maximum length a table name can be, expressed in bytes.\n", + " * `NON_NULLABLE_COLUMNS`    : A boolean value indicating whether the database server supports the ability to define columns that are __NOT NULL__ (`True`) or not (`False`).\n", + " * `PROCEDURES`                        : A boolean value indicating whether the database server supports the use of the __CALL__ statement to invoke stored procedures (`True`) or not (`False`).\n", + " * `SPECIAL_CHARS`                  : A string containing all characters other than __A-Z__, __0-9__, and underscore (__\\___) that can be used in an identifier name.\n", + " * `SQL_CONFORMANCE`              : The level of conformance to the __ANSI/ISO SQL-92__ specification that is offered by the database server. Valid values are:

\n", + " * `ENTRY`                : Entry-level SQL-92 compliance is provided.\n", + " * `FIPS127`            : FIPS-127-2 transitional compliance is provided.\n", + " * `FULL`                  : Full level SQL-92 compliance is provided.\n", + " * `INTERMEDIATE`  : Intermediate level SQL-92 compliance is provided.\n", + "

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.server_info()__ API is used to obtain detailed information about an IBM Db2 database server." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the ibm-UDOO-x86 server ... Done!\n", + "\n", + "Obtaining information about the server ... Done!\n", + "\n", + "Server details:\n", + "_____________________________________________________________________________\n", + "Db2 database server name : DB2/LINUXX8664\n", + "Db2 software version : 11.01.0404\n", + "Db2 instance name : DB2\n", + "Database codepage used : 1208\n", + "Database name : \n", + "Isolation levels supported : Uncommitted Read (UR)\n", + " Cursor Stability (CS)\n", + " Read Stability (RS)\n", + " Repeatable Read (RR)\n", + "Default isolation level used : CS\n", + "Identifier delimiter character : \"\n", + "Use of % and _ as wildcards supported : Yes\n", + "Maximum column name length : 128 bytes\n", + "Maximum SQL identifier length : 128 characters\n", + "Maximum index size (combined columns) : 1024 bytes\n", + "Maximum procedure name length : 128 bytes\n", + "Maximum row size : 32677 bytes\n", + "Maximum schema name length : 128 bytes\n", + "Maximum SQL statement length : 2097152 bytes\n", + "Maximum table name length : 128 bytes\n", + "NOT NULL columns supported : Yes\n", + "CALL statement supported : Yes\n", + "Characters supported in identifier names : A-Z, 0-9, _, @, and #\n", + "ANSI/ISO SQL-92 conformance level : FIPS-127-2 transitional compliance\n", + "\n", + "Reserved keywords:\n", + "____________________________________________________________________________________________\n", + "\n", + "AFTER ALIAS ALLOW APPLICATION ASSOCIATE \n", + "ASUTIME AUDIT AUX AUXILIARY BEFORE \n", + "BINARY BUFFERPOOL CACHE CALL CALLED \n", + "CAPTURE CARDINALITY CCSID CLUSTER COLLECTION \n", + "COLLID COMMENT CONCAT CONDITION CONTAINS \n", + "COUNT_BIG CURRENT_LC_CTYPE CURRENT_PATH CURRENT_SERVER CURRENT_TIMEZONE \n", + "CYCLE DATA DATABASE DAYS DB2GENERAL \n", + "DB2GENRL DB2SQL DBINFO DEFAULTS DEFINITION \n", + "DETERMINISTIC DISALLOW DO DSNHATTR DSSIZE \n", + "DYNAMIC EACH EDITPROC ELSEIF ENCODING \n", + "END-EXEC1 ERASE EXCLUDING EXIT FENCED \n", + "FIELDPROC FILE FINAL FREE FUNCTION \n", + "GENERAL GENERATED GRAPHIC HANDLER HOLD \n", + "HOURS IF INCLUDING INCREMENT INHERIT \n", + "INOUT INTEGRITY ISOBID ITERATE JAR \n", + "JAVA LABEL LC_CTYPE LEAVE LINKTYPE \n", + "LOCALE LOCATOR LOCATORS LOCK LOCKMAX \n", + "LOCKSIZE LONG LOOP MAXVALUE MICROSECOND \n", + "MICROSECONDS MINUTES MINVALUE MODE MODIFIES \n", + "MONTHS NEW NEW_TABLE NOCACHE NOCYCLE \n", + "NODENAME NODENUMBER NOMAXVALUE NOMINVALUE NOORDER \n", + "NULLS NUMPARTS OBID OLD OLD_TABLE \n", + "OPTIMIZATION OPTIMIZE OUT OVERRIDING PACKAGE \n", + "PARAMETER PART PARTITION PATH PIECESIZE \n", + "PLAN PRIQTY PROGRAM PSID QUERYNO \n", + "READS RECOVERY REFERENCING RELEASE RENAME \n", + "REPEAT RESET RESIGNAL RESTART RESULT \n", + "RESULT_SET_LOCATOR RETURN RETURNS ROUTINE ROW \n", + "RRN RUN SAVEPOINT SCRATCHPAD SECONDS \n", + "SECQTY SECURITY SENSITIVE SIGNAL SIMPLE \n", + "SOURCE SPECIFIC SQLID STANDARD START \n", + "STATIC STAY STOGROUP STORES STYLE \n", + "SUBPAGES SYNONYM SYSFUN SYSIBM SYSPROC \n", + "SYSTEM TABLESPACE TRIGGER TYPE UNDO \n", + "UNTIL VALIDPROC VARIABLE VARIANT VCAT \n", + "VOLUMES WHILE WLM YEARS \n", + "\n", + "Disconnecting from the ibm-UDOO-x86 server ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-server_info.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.server_info() API. #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "svrConnection = None\n", + "serverInfo = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server\n", + "conn = Db2ConnectionMgr('SERVER', '', '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " svrConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Obtain Information About The Db2 Server Being Used\n", + "print(\"Obtaining information about the server ... \", end=\"\")\n", + "try:\n", + " serverInfo = ibm_db.server_info(svrConnection)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If Information About The Server Could Not Be Obtained, Display An Error Message \n", + "if serverInfo is False:\n", + " print(\"\\nERROR: Unable to obtain server information.\\n\")\n", + "\n", + "# Otherwise, Complete The Status Message; Then Format And Display The Data Retrieved\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + " # Display A Report Header\n", + " print(\"Server details:\")\n", + " print(\"_____________________________________________________________________________\")\n", + " \n", + " # Display The Server Data\n", + " print(\"Db2 database server name : {}\" .format(serverInfo.DBMS_NAME))\n", + " print(\"Db2 software version : {}\" .format(serverInfo.DBMS_VER))\n", + " print(\"Db2 instance name : {}\" .format(serverInfo.INST_NAME))\n", + " print(\"Database codepage used : {}\" .format(serverInfo.DB_CODEPAGE))\n", + " print(\"Database name : {}\" .format(serverInfo.DB_NAME))\n", + "\n", + " print(\"Isolation levels supported : \", end=\"\")\n", + " for loopCounter in range(0, len(serverInfo.ISOLATION_OPTION)):\n", + " if serverInfo.ISOLATION_OPTION[loopCounter] == 'UR':\n", + " print(\"Uncommitted Read (UR)\", end=\"\")\n", + " elif serverInfo.ISOLATION_OPTION[loopCounter] == 'CS':\n", + " print(\"Cursor Stability (CS)\", end=\"\")\n", + " elif serverInfo.ISOLATION_OPTION[loopCounter] == 'RS':\n", + " print(\"Read Stability (RS)\", end=\"\")\n", + " elif serverInfo.ISOLATION_OPTION[loopCounter] == 'RR':\n", + " print(\"Repeatable Read (RR)\", end=\"\")\n", + " elif serverInfo.ISOLATION_OPTION[loopCounter] == 'NC':\n", + " print(\"No Commit\", end=\"\")\n", + " if loopCounter < len(serverInfo.ISOLATION_OPTION) - 1:\n", + " print(\"\\n\" + \" \" * 43, end=\"\")\n", + " print()\n", + "\n", + " print(\"Default isolation level used : \", end=\"\")\n", + " if serverInfo.DFT_ISOLATION == 'NC':\n", + " print(\"No Commit\")\n", + " else:\n", + " print(\"{}\" .format(serverInfo.DFT_ISOLATION))\n", + "\n", + " print(\"Identifier delimiter character : \", end=\"\")\n", + " print(\"{}\" .format(serverInfo.IDENTIFIER_QUOTE_CHAR))\n", + "\n", + " print(\"Use of % and _ as wildcards supported : \", end=\"\")\n", + " if serverInfo.LIKE_ESCAPE_CLAUSE == True:\n", + " print(\"Yes\")\n", + " else:\n", + " print(\"No\")\n", + "\n", + " print(\"Maximum column name length : \", end=\"\")\n", + " print(\"{:<7} bytes\" .format(serverInfo.MAX_COL_NAME_LEN))\n", + " print(\"Maximum SQL identifier length : \", end=\"\")\n", + " print(\"{:<7} characters\" .format(serverInfo.MAX_IDENTIFIER_LEN))\n", + " print(\"Maximum index size (combined columns) : \", end=\"\")\n", + " print(\"{:<7} bytes\" .format(serverInfo.MAX_INDEX_SIZE))\n", + " print(\"Maximum procedure name length : \", end=\"\")\n", + " print(\"{:<7} bytes\" .format(serverInfo.MAX_PROC_NAME_LEN))\n", + " print(\"Maximum row size : \", end=\"\")\n", + " print(\"{:<7} bytes\" .format(serverInfo.MAX_ROW_SIZE))\n", + " print(\"Maximum schema name length : \", end=\"\")\n", + " print(\"{:<7} bytes\" .format(serverInfo.MAX_SCHEMA_NAME_LEN))\n", + " print(\"Maximum SQL statement length : \", end=\"\")\n", + " print(\"{:<7} bytes\" .format(serverInfo.MAX_STATEMENT_LEN))\n", + " print(\"Maximum table name length : \", end=\"\")\n", + " print(\"{:<7} bytes\" .format(serverInfo.MAX_TABLE_NAME_LEN))\n", + "\n", + " print(\"NOT NULL columns supported : \", end=\"\")\n", + " if serverInfo.NON_NULLABLE_COLUMNS == True:\n", + " print(\"Yes\")\n", + " else:\n", + " print(\"No\")\n", + " print(\"CALL statement supported : \", end=\"\")\n", + " if serverInfo.PROCEDURES == True:\n", + " print(\"Yes\")\n", + " else:\n", + " print(\"No\")\n", + "\n", + " print(\"Characters supported in identifier names : A-Z, 0-9, _, \", end=\"\")\n", + " tempString = (\", \".join(serverInfo.SPECIAL_CHARS))\n", + " endingPos = tempString.find(tempString[-1])\n", + " tempString = tempString[:int(endingPos)]\n", + " tempString += \"and \" + serverInfo.SPECIAL_CHARS[-1]\n", + " print(tempString)\n", + "\n", + " print(\"ANSI/ISO SQL-92 conformance level : \", end=\"\")\n", + " if serverInfo.SQL_CONFORMANCE == 'ENTRY':\n", + " print(\"Entry-level compliance\\n\")\n", + " elif serverInfo.SQL_CONFORMANCE == 'INTERMEDIATE':\n", + " print(\"Intermediate-level compliance\\n\")\n", + " elif serverInfo.SQL_CONFORMANCE == 'FULL':\n", + " print(\"Full compliance\\n\")\n", + " elif serverInfo.SQL_CONFORMANCE == 'FIPS127':\n", + " print(\"FIPS-127-2 transitional compliance\\n\")\n", + "\n", + " # Display Another Header, Followed By A Five-Column List Of Reserved Keywords\n", + " print(\"Reserved keywords:\")\n", + " print('_' * 92 + \"\\n\")\n", + " loopCounter = 0\n", + " while loopCounter < len(serverInfo.KEYWORDS):\n", + " colNumber = 0\n", + " while colNumber < 5:\n", + " print(\"{:<19}\".format(serverInfo.KEYWORDS[loopCounter]), end=\"\")\n", + " colNumber += 1\n", + " loopCounter += 1\n", + " if colNumber is 5:\n", + " print()\n", + " if loopCounter is len(serverInfo.KEYWORDS):\n", + " break\n", + "\n", + "# End The Last Row And Add A Blank Line To The End Of The Report\n", + "print(\"\\n\")\n", + "\n", + "# Close The Server Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-set_option.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-set_option.ipynb new file mode 100644 index 0000000..49689d1 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-set_option.ipynb @@ -0,0 +1,631 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.set_option()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Assign a value to a connection or statement option (attribute)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`bool ibm_db.set_option( mixed `*`resource,`*` dictionary `*`options,`*` int `*`resourceType`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*resource*__            : A valid `IBM_DBConnection` or `IBM_DBStatement` object. \n", + "* __options__              : A dictionary containing key-value pairs for the attributes that are to be set. Valid keys for `IBM_DBConnection` objects are:

\n", + " \n", + " * `ibm_db.SQL_ATTR_AUTOCOMMIT`                               : Specifies whether __AUTOCOMMIT__ mode is to be used or not; `ibm_db.SQL_AUTOCOMMIT_ON` will turn __AUTOCOMMIT__ behavior __ON__ and `ibm_db.SQL_AUTOCOMMIT_OFF` will turn it __OFF__.\n", + " * `ibm_db.SQL_ATTR_CASE`                                           : The case that column names will be returned in; `ibm_db.CASE_NATURAL` will cause column names to be returned in natural case, `ibm_db.CASE_LOWER` will cause them to be returned in lower case, and `ibm_db.CASE_UPPER` will cause them to be returned in upper case. *(This attribute can only be used with Db2 databases on OS/390 or z/OS servers.)*\n", + " * `ibm_db.SQL_ATTR_CURRENT_SCHEMA`                       : The name of the schema to use, by default, when performing operations that require a schema name and one is not provided.\n", + " * `ibm_db.SQL_ATTR_INFO_ACCTSTR`                           : A null-terminated user-defined string, up to 255 characters in length, that contains the client accounting string that is to be sent to the currently connected Db2 server or database. *This option can only be set after a connection has been established.*\n", + " * `ibm_db.SQL_ATTR_INFO_APPLNAME`                         : A null-terminated user-defined character string, up to 255 characters in length, that contains the client application name that is to be sent to the currently connected Db2 server or database. *This option can only be set after a connection has been established.*\n", + " * `ibm_db.SQL_ATTR_INFO_PROGRAMNAME`                   : A null-terminated user-defined character string, up to 20 bytes in length, that is used to specify the name of the application running on the client. *This option can only be set before a connection has been established.*\n", + " * `ibm_db.SQL_ATTR_INFO_USERID`                             : The client user ID (accounting user ID) that is to be sent to the currently connected Db2 server or database. This information is used for identification purposes only—not for authentication. *This option can only be set after a connection has been established.*\n", + " * `ibm_db.SQL_ATTR_INFO_WRKSTNNAME`                     : A null-terminated user-defined string, up to 255 characters in length, that contains the client workstation name that is to be sent to the currently connected Db2 server or database. *This option can only be set after a connection has been established.*\n", + " * `ibm_db.SQL_ATTR_USE_TRUSTED_CONTEXT`             : Specifies whether the connection to a Db2 server or database is to be treated as a trusted connection; `ibm_db.SQL_TRUE` indicates the connection can be trusted and `ibm_db.SQL_FALSE` indicates the connection should not to be treated as a trusted connection. *This option can only be set before a connection has been established.* \n", + " * `ibm_db.SQL_ATTR_TRUSTED_CONTEXT_USERID`       : A user defined character string containing the client user ID (accounting user ID) that an *existing* trusted connection is to be switched to — __Do not use this option to create a trusted connection!__ *This option can only be set after a connection has been established.* \n", + " * `ibm_db.SQL_ATTR_TRUSTED_CONTEXT_PASSWORD`   : A user defined string containing the password for the user ID provided via the __ibm_db.SQL_ATTR_TRUSTED_CONTEXT_USERID__ option. This option must be provided if the database server requires a password when switching users on an existing trusted connection. *This option can only be set after a connection has been established.*

\n", + " \n", + " Valid keys for `IBM_DBStatement` objects are:

\n", + " \n", + " * `ibm_db.SQL_ATTR_CURSOR_TYPE`                             : Specifies the type of cursor that is to be used for processing result sets. Valid values are:\n", + " * `ibm_db.SQL_CURSOR_FORWARD_ONLY`                 : A forward only cursor should be used (i.e., a cursor that only scrolls forward).\n", + " * `ibm_db. SQL_CURSOR_KEYSET_DRIVEN`             : A keyset-driven cursor should be used.\n", + " * `ibm_db.SQL_CURSOR_STATIC`                             : A static cursor should be used.\n", + " * `ibm_db.SQL_CURSOR_DYNAMIC`                           : A dynamic, scrollable cursor that detects all changes to the result set, should be used. Dynamic cursors are only supported by Db2 for z/OS servers.\n", + " * `ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH`                 : Enables Db2 to determine the number of rows that are returned by a query (so the entire result set can be prefetched into memory, when possible); `ibm_db.SQL_ROWCOUNT_PREFETCH_ON` will turn this behavior __ON__ and `ibm_db.SQL_ROWCOUNT_PREFETCH_OFF` will turn it __OFF__.\n", + " * `ibm_db.SQL_ATTR_QUERY_TIMEOUT`                         : The number of seconds to wait for an SQL statement to execute before aborting and returning to the application. This option can be used to terminate long running queries — the default value of __0__ means an application will wait indefinitely for the server to complete execution.

\n", + " \n", + "* __resourceType__    : Identifies whether the value provided in the __*resource*__ parameter is an `IBM_DBConnection` object or an `IBM_DBStatement` object. Valid values for this parameter are:

\n", + " \n", + " * `0`   : The __*resource*__ parameter contains a valid `IBM_DBStatement` object.\n", + " * `1`   : The __*resource*__ parameter contains a valid `IBM_DBConnection` object." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* `True`      : The connection or statement option(s) specified were set. \n", + "* `False`    : The connection or statement option(s) specified were not set." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.set_option()__ API is used to assign a value to a connection or statement option (attribute). Once set, an attribute's value remains in effect until it is changed by another call to this API or the `IBM_DBConnection` or `IBM_DBStatement` object used is deleted.

\n", + "\n", + "It is important to note that options cannot be set for result set resources." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Examples:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "###     Example 1: Set connection options" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the 'SAMPLE' database ... Done!\n", + "\n", + "Assigning values to four different connection options ... Done!\n", + "\n", + "Connection option settings:\n", + "\n", + "OPTION SETTING\n", + "________________________ ____________________\n", + "SQL_ATTR_INFO_ACCTSTR RESANDERS@IBM\n", + "SQL_ATTR_INFO_APPLNAME ibm_db-set_option.py\n", + "SQL_ATTR_INFO_USERID db2inst1\n", + "SQL_ATTR_INFO_WRKSTNNAME ibm_UDOO_X86\n", + "\n", + "Disconnecting from the 'SAMPLE' database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-set_option_CONNECTION.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.set_option() API to #\n", + "# assign values to some of the connection options available. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.connect() #\n", + "# ibm_db.get_option() #\n", + "# ibm_db.close() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "returnCode = False\n", + "\n", + "# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database\n", + "# Is About To Be Made\n", + "print(\"\\nConnecting to the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + "\n", + "# Construct The String That Will Be Used To Establish A Db2 Database Connection\n", + "connString = \"ATTACH=FALSE\" # Attach To A Database; Not A Server\n", + "connString += \";DATABASE=\" + dbName # Required To Connect To A Database \n", + "connString += \";PROTOCOL=TCPIP\"\n", + "connString += \";UID=\" + userID\n", + "connString += \";PWD=\" + passWord\n", + "\n", + "# Attempt To Establish A Connection To The Database Specified\n", + "try:\n", + " dbConnection = ibm_db.connect(connString, '', '')\n", + "except Exception:\n", + " pass\n", + "\n", + "# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit\n", + "if dbConnection is None:\n", + " print(\"\\nERROR: Unable to connect to the \\'\" + dbName + \"\\' database.\")\n", + " print(\"Connection string used: \" + connString + \"\\n\")\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Create A Dictionary That Contains Values For The Connection Options That Can Only Be Set \n", + "# After A Database Connection Is Established\n", + "connectOptions = {ibm_db.SQL_ATTR_INFO_ACCTSTR : 'RESANDERS@IBM', \n", + " ibm_db.SQL_ATTR_INFO_APPLNAME : 'ibm_db-set_option.py',\n", + " ibm_db.SQL_ATTR_INFO_USERID : 'db2inst1',\n", + " ibm_db.SQL_ATTR_INFO_WRKSTNNAME : 'ibm_UDOO_X86'}\n", + "\n", + "# Attempt To Set The Connection Options Specified\n", + "print(\"Assigning values to four different connection options ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.set_option(dbConnection, connectOptions, 1)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Connection Options Could Not Be Set, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to set the connection options specified.\\n\")\n", + " if not dbConnection is None:\n", + " ibm_db.close(dbConnection)\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Display A Report Header\n", + "print(\"Connection option settings:\\n\")\n", + "print(\"OPTION SETTING\")\n", + "print(\"________________________ ____________________\")\n", + "\n", + "# Retrieve And Display The Accounting String That Was Defined For The Client\n", + "value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_ACCTSTR, 1)\n", + "print(\"SQL_ATTR_INFO_ACCTSTR \" + value)\n", + "\n", + "\n", + "# Retrieve And Display The Application Name That Was Defined For The Client\n", + "value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_APPLNAME, 1)\n", + "print(\"SQL_ATTR_INFO_APPLNAME \" + value)\n", + "\n", + "# Retrieve And Display The User ID That Was Defined For The Client\n", + "value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_USERID, 1)\n", + "print(\"SQL_ATTR_INFO_USERID \" + value)\n", + "\n", + "# Retrieve And Display The Workstation Name That Was Defined For The Client\n", + "value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_WRKSTNNAME, 1)\n", + "print(\"SQL_ATTR_INFO_WRKSTNNAME \" + value)\n", + "\n", + "# Add A Blank Line To The End Of The Report\n", + "print()\n", + "\n", + "# Attempt To Close The Db2 Database Connection That Was Opened Earlier\n", + "if not dbConnection is None:\n", + " print(\"Disconnecting from the \\'\" + dbName + \"\\' database ... \", end=\"\")\n", + " try:\n", + " returnCode = ibm_db.close(dbConnection)\n", + " except Exception:\n", + " pass\n", + "\n", + " # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit\n", + " if returnCode is False:\n", + " print(\"\\nERROR: Unable to disconnect from the \" + dbName + \" database.\")\n", + " exit(-1)\n", + "\n", + " # Otherwise, Complete The Status Message\n", + " else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "##     Example 2: Set statement options" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Preparing the SQL statement \"SELECT * FROM employee WHERE edlevel > 17\" ... Done!\n", + "\n", + "Executing the prepared SQL statement ... Done!\n", + "\n", + "Unable to obtain information about the number of rows returned.\n", + "\n", + "Freeing system resources associated with the prepared statement ... Done!\n", + "\n", + "Turning SQL_ATTR_ROWCOUNT_PREFETCH behavior ON ... Done!\n", + "\n", + "Executing the prepared SQL statement again ... Done!\n", + "\n", + "Number of rows returned by the query: 9\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-set_option_STATEMENT.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.set_option() API to #\n", + "# assign a value to one of the statement options available. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.prepare() #\n", + "# ibm_db.execute() #\n", + "# ibm_db.num_rows() #\n", + "# ibm_db.free_result() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "preparedStmt = False\n", + "resultSet = False\n", + "returnCode = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Define The SQL Statement That Is To Be Executed\n", + "sqlStatement = \"SELECT * FROM employee WHERE edlevel > 17\"\n", + "\n", + "# Prepare The SQL Statement Just Defined\n", + "print(\"Preparing the SQL statement \\\"\" + sqlStatement + \"\\\" ... \", end=\"\")\n", + "try:\n", + " preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit\n", + "if preparedStmt is False:\n", + " print(\"\\nERROR: Unable to prepare the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Execute The SQL Statement Just Prepared\n", + "print(\"Executing the prepared SQL statement ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.execute(preparedStmt)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Just Executed\n", + "# (This Information Should Not Be Available)\n", + "try:\n", + " numRows = ibm_db.num_rows(preparedStmt)\n", + "except Exception:\n", + " pass\n", + " \n", + "# Display An Appropriate Message, Based On The Information Returned\n", + "if numRows <= 0:\n", + " print(\"Unable to obtain information about the number of rows returned.\\n\")\n", + "else:\n", + " print(\"Number of rows returned by the query: \" + str(numRows) + \"\\n\")\n", + "\n", + "# Free System Resources That Are Associated With The Prepared Statement And Result Set Produced\n", + "print(\"Freeing system resources associated with the prepared statement ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.free_result(preparedStmt)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Appropriate System Resources Could Not Be Freed, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to free the appropriate system resources.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Create A Dictionary That Contains The Value Needed To Turn Row Prefetch Behavior On;\n", + "# This Enables Db2 To Determine The Number Of Rows That Are Returned By A Query (So The\n", + "# Entire Result Set Can Be Prefetched Into Memory, When Possible) \n", + "stmtOption = {ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON}\n", + "\n", + "# Attempt To Set The Statement Option Specified\n", + "print(\"Turning SQL_ATTR_ROWCOUNT_PREFETCH behavior ON ... \", end=\"\")\n", + "try:\n", + " returnCode = ibm_db.set_option(preparedStmt, stmtOption, 0)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Statement Option Could Not Be Set, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to set the statement option specified.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Execute The Prepared SQL Statement Again\n", + "print(\"Executing the prepared SQL statement again ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.execute(preparedStmt)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement specified.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Again\n", + "# (This Time, The Information Should Be Available)\n", + "try:\n", + " numRows = ibm_db.num_rows(preparedStmt)\n", + "except Exception:\n", + " pass\n", + "\n", + "# Display An Appropriate Message, Based On The New Information Returned\n", + "if numRows <= 0:\n", + " print(\"Unable to obtain information about the number of rows returned.\\n\")\n", + "else:\n", + " print(\"Number of rows returned by the query: \" + str(numRows) + \"\\n\")\n", + "\n", + "# Free The Appropriate System Resources Again\n", + "try:\n", + " returnCode = ibm_db.free_result(preparedStmt)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Appropriate System Resources Could Not Be Freed, Display An Error Message And Exit \n", + "if returnCode is False:\n", + " print(\"\\nERROR: Unable to free the appropriate system resources.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + " \n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-special_columns.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-special_columns.ipynb new file mode 100644 index 0000000..bb246e2 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-special_columns.ipynb @@ -0,0 +1,368 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.special_columns()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve a list of unique row identifier columns and their associated metadata, for a table." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.special_columns( IBM_DBConnection `*`connection,`*` string `*`qualifierName,`*
` string `*`schemaName,`*` string `*`tableName,`*` int `*`scope`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__        : A valid Db2 server or database connection. \n", + "* __qualifierName__    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value `None` or an empty string (`''`) for Db2 databases on other operating systems. \n", + "* __schemaName__     : The name of the schema that contains the table(s) that unique row identifier column information is to be obtained for.\n", + "* __tableName__          : The name of the table that unique identifier column information is to be obtained for. \n", + "* __scope__                  : The minimum duration for which the unique row identifier column is guaranteed to point to the same row. Valid values for this parameter are:

\n", + " \n", + " * `0`   : The row identifier is guaranteed to be valid only while the cursor is positioned on the current row.\n", + " * `1`   : The row identifier is guaranteed to be valid for the duration of the transaction.\n", + " * `2`   : The row identifier is guaranteed to be valid for the duration of the connection." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an IBM_DBStatement with a result set that contains the following information:

\n", + "\n", + " * `SCOPE`                      : A value that indicates the minimum duration for which the unique row identifier is guaranteed to point to the same row. Valid values for this field are:

\n", + " \n", + " * `0`   : The row identifier is guaranteed to be valid only while the cursor is positioned on the current row.\n", + " * `1`   : The row identifier is guaranteed to be valid for the duration of the transaction.\n", + " * `2`   : The row identifier is guaranteed to be valid for the duration of the connection.

\n", + " \n", + " * `COLUMN_NAME`         : The name of the column that is the primary key *or* part of the primary key of the table.\n", + " * `DATA_TYPE`              : An integer value that represents the SQL data type of the column. On Linux and UNIX systems, valid values for this field can be found in the file */opt/ibm/db2/V11.1/include/sqlcli.h*.\n", + " * `TYPE_NAME`              : The data source-specific string representation of the SQL data type of the column.\n", + " * `COLUMN_SIZE`          : The maximum number of bytes needed to display the column's data as a string.\n", + " * `BUFFER_LENGTH`      : The maximum number of bytes needed to store the column's data in an application variable.\n", + " * `DECIMAL_DIGITS`    : The scale (i.e., total number of significant digits to the right of the decimal point) of the column - provided the column has a numerical data type. If the column does not have a numerical data type, this field will contain the value `None`.\n", + " * `NUM_PREC_RADIX`    : A numerical value that indicates whether the column's data type represents an exact numeric data type (`10`) or an approximate numeric data type (`2`). If the column does not have a numerical data type, this field will contain the value `None`.\n", + " * `PSEUDO_COLUMN`      : Indication of whether the column is a pseudo-column (a \"column\" that returns a value when selected, but is not an actual column of the table) or not. This field will always contain the value `1`, which means the column is NOT a pseudo-column.

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.special_columns()__ API is used to retrieve information about unique row identifier columns that have been created for a table. (Columns used to create a primary key or unique index are referred to as *unique row identifier columns*.)\n", + "\n", + "The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Obtaining information about unique row identifier columns that have been\n", + "defined for the DB2INST1.EMPLOYEE table ... Done!\n", + "\n", + "Primary key/unique index 1 details:\n", + "___________________________________\n", + "Column name : EMPNO\n", + "Data type : CHAR\n", + "SQL data type : SQL_CHAR\n", + "Column size : 6\n", + "Buffer size : 6\n", + "Scale (decimal digits) : None\n", + "Scope : Row ID is valid only while the\n", + " cursor is positioned on the row\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-special_columns.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.special_columns() #\n", + "# API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.fetch_assoc() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "schemaName = userID.upper()\n", + "tableName = \"EMPLOYEE\"\n", + "resultSet = False\n", + "dataRecord = False\n", + "sqlDataTypes = {0 : \"SQL_UNKNOWN_TYPE\", 1 : \"SQL_CHAR\", 2 : \"SQL_NUMERIC\", 3 : \"SQL_DECIMAL\",\n", + " 4 : \"SQL_INTEGER\", 5 : \"SQL_SMALLINT\", 6 : \"SQL_FLOAT\", 7 : \"SQL_REAL\", 8 : \"SQL_DOUBLE\",\n", + " 9 : \"SQL_DATETIME\", 12 : \"SQL_VARCHAR\", 16 : \"SQL_BOOLEAN\", 19 : \"SQL_ROW\", \n", + " 91 : \"SQL_TYPE_DATE\", 92 : \"SQL_TYPE_TIME\", 93 : \"SQL_TYPE_TIMESTAMP\",\n", + " 95 : \"SQL_TYPE_TIMESTAMP_WITH_TIMEZONE\", -8 : \"SQL_WCHAR\", -9 : \"SQL_WVARCHAR\",\n", + " -10 : \"SQL_WLONGVARCHAR\", -95 : \"SQL_GRAPHIC\", -96 : \"SQL_VARGRAPHIC\",\n", + " -97 : \"SQL_LONGVARGRAPHIC\", -98 : \"SQL_BLOB\", -99 : \"SQL_CLOB\", -350 : \"SQL_DBCLOB\",\n", + " -360 : \"SQL_DECFLOAT\", -370 : \"SQL_XML\", -380 : \"SQL_CURSORHANDLE\", -400 : \"SQL_DATALINK\",\n", + " -450 : \"SQL_USER_DEFINED_TYPE\"}\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Retrieve Information About Unique Row Identifier Columns That Have Been \n", + "# Defined For The Table Specified\n", + "print(\"Obtaining information about unique row identifier columns that have been\")\n", + "print(\"defined for the \" + schemaName + \".\" + tableName + \" table ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.special_columns(dbConnection, None, schemaName, tableName, 0)\n", + "\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit\n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired\\n.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# As Long As There Are Records (That Were Produced By The ibm_db.special_columns API), ...\n", + "noData = False\n", + "loopCounter = 1\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Information Retrieved\n", + " else:\n", + "\n", + " # Display Record Header Information\n", + " print(\"Primary key/unique index \" + str(loopCounter) + \" details:\")\n", + " print(\"___________________________________\")\n", + "\n", + " # Display The Information Stored In The Data Record Retrieved\n", + " print(\"Column name : {}\" .format(dataRecord['COLUMN_NAME']))\n", + " print(\"Data type : {}\" .format(dataRecord['TYPE_NAME']))\n", + " print(\"SQL data type : \", end=\"\")\n", + " print(sqlDataTypes.get(dataRecord['DATA_TYPE']))\n", + " print(\"Column size : {}\" .format(dataRecord['COLUMN_SIZE']))\n", + " print(\"Buffer size : {}\" .format(dataRecord['BUFFER_LENGTH']))\n", + " print(\"Scale (decimal digits) : {}\" .format(dataRecord['DECIMAL_DIGITS']))\n", + "\n", + " print(\"Scope : \", end=\"\")\n", + " if dataRecord['SCOPE'] == 0:\n", + " print(\"Row ID is valid only while the\\n\" + \" \" * 25, end=\"\")\n", + " print(\"cursor is positioned on the row\")\n", + " elif dataRecord['SCOPE'] == 1:\n", + " print(\"Row ID is valid for the\\n\" + \" \" * 25, end=\"\")\n", + " print(\"duration of the transaction\")\n", + " elif dataRecord['SCOPE'] == 2:\n", + " print(\"Row ID is valid for the\\n\" + \" \" * 25, end=\"\")\n", + " print(\"duration of the connection\")\n", + "\n", + " # Increment The loopCounter Variable And Print A Blank Line To Separate The\n", + " # Records From Each Other\n", + " loopCounter += 1\n", + " print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-statistics.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-statistics.ipynb new file mode 100644 index 0000000..bd08d35 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-statistics.ipynb @@ -0,0 +1,415 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.statistics()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve statistical information for a table and its associated indexes." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.statistics( IBM_DBConnection `*`connection,`*` string `*`qualifierName,`*
` string `*`schemaName,`*` string `*`tableName,`*` bool `*`uniqueIndicator`*` )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__            : A valid Db2 server or database connection. \n", + "* __qualifierName__        : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value `None` or an empty string (`''`) for Db2 databases on other operating systems. \n", + "* __schemaName__         : The name of the schema that contains the table that statistical information is to be obtained for. To isolate the search for information to the schema for the current user, provide the value `None` or an empty string.\n", + "* __tableName__              : The name of the table that statistical information is to be obtained for. \n", + "* __uniqueIndicator__     : A value that indicates whether statistical information should be retreived for all indexes that have been defined for the table specified—or just for unique indexes. Valid values for this parameter are:

\n", + " \n", + " * `True`     : Only retrieve information for unique indexes.\n", + " * `False`   : Retrieve information for all indexes." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an IBM_DBStatement with a result set that contains the following information:

\n", + "\n", + " * `TYPE`                          : A value that identifies the type of information contained in the current row (record) in this result set. Valid values for this field are:

\n", + " \n", + " * `ibm_db.SQL_TABLE_STAT`             : The current row contains statistical information about the table itself.\n", + " * `ibm_db.SQL_INDEX_CLUSTERED`   : The current row contains statistical information for a clustered index.\n", + " * `ibm_db.SQL_INDEX_OTHER`           : The current row contains statistical information for some other type of index.

\n", + " \n", + " * `TABLE_CAT`                : The name of the catalog associated with the schema and table the statistical information is for; Db2 does not use catalogs so this field will always contain the value `None`. *(Db2 databases on OS/390 or z/OS servers can return information in this field.)*\n", + " * `TABLE_SCHEM`            : The name of the schema for the table the statistical information is associated with.\n", + " * `TABLE_NAME`              : The name of the table to which the statistical information applies.\n", + " * `INDEX_NAME`              : The name of the index to which the statistical information applies. \n", + " * `INDEX_QUALIFIER`    : The character string that would have to be prepended to the index name (__INDEX_NAME__) to fully qualify the name in a `DROP INDEX` statement. \n", + " * `NON_UNIQUE`              : A value that indicates whether the index allows or prohibits duplicate values. Valid values for this field are:

\n", + " \n", + " * `ibm_db.SQL_TRUE`     : The index allows duplicate values. \n", + " * `ibm_db.SQL_FALSE`   : The index values must be unique.\n", + " * `None`                           : The __TYPE__ field indicates the current row contains statistical information about the table - not an index.

\n", + " \n", + " * `ORDINAL_POSITION`  : The column's ordinal position in the index, starting from 1. If the __TYPE__ field indicates the current row contains statistical information about the table, this field will contain the value `None`.\n", + " * `COLUMN_NAME`             : The name of the column in the index. If the __TYPE__ field indicates the current row contains statistical information about the table, this field will contain the value `None`. \n", + " * `ASC_OR_DESC`             : A value that identifies the sort sequence that is used to order the column's data. Valid values for this field are:

\n", + " \n", + " * `'A'`     : The column's data is sorted in ascending order.\n", + " * `'D'`     : The column's data is sorted in descending order.\n", + " * `None`   : The __TYPE__ field indicates the current row contains statistical information about the table - not an index.

\n", + " \n", + " * `CARDINALITY`            : If the __TYPE__ field indicates the current row contains statistical information about the table, this field will contain the number of rows found in the table. If the current row contains statistical information about an index, this field will contain the number of unique values found in the index.\n", + " * `PAGES`                        : The number of pages used to store the table or index.\n", + " * `FILTER_CONDITION`  : Identifies the filter condition used if the index is a filtered index; Db2 does not support filtered indexes so this field will always contain the value `None`.\n", + "

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.statistics()__ API is used to retrieve statistical information for a table and its associated indexes. When invoked, this API can return two types of information:

\n", + " \n", + "* Statistical information about the table itself (*if that information is available*).\n", + "* Statistical information about any indexes that have been defined for the table.

\n", + "\n", + "The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Obtaining statistics for the DB2INST1.EMPLOYEE table ... Done!\n", + "\n", + "Record number 1 details:\n", + "______________________________________________\n", + "Type of data : Index\n", + "Table schema : DB2INST1\n", + "Table name : EMPLOYEE\n", + "Index qualifier : DB2INST1\n", + "Index name : PK_EMPLOYEE\n", + "Column name : EMPNO\n", + "Column position in index : 1\n", + "Index used to enforce uniqueness : No\n", + "Data order : Ascending\n", + "Number of unique values : 42\n", + "Number of pages used : 1\n", + "\n", + "Record number 2 details:\n", + "______________________________________________\n", + "Type of data : Index\n", + "Table schema : DB2INST1\n", + "Table name : EMPLOYEE\n", + "Index qualifier : DB2INST1\n", + "Index name : XEMP2\n", + "Column name : WORKDEPT\n", + "Column position in index : 1\n", + "Index used to enforce uniqueness : Yes\n", + "Data order : Ascending\n", + "Number of unique values : 8\n", + "Number of pages used : 1\n", + "\n", + "Record number 3 details:\n", + "______________________________________________\n", + "Type of data : Table\n", + "Table schema : DB2INST1\n", + "Table name : EMPLOYEE\n", + "Index qualifier : None\n", + "Index name : None\n", + "Column name : None\n", + "Column position in index : None\n", + "Number of rows (records) : 42\n", + "Number of pages used : 1\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-statistics.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.statistics() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.fetch_assoc() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "schemaName = userID.upper()\n", + "tableName = \"EMPLOYEE\"\n", + "resultSet = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Retrieve Information About The Indexes And Statistics That Exist For A \n", + "# Specified Table\n", + "print(\"Obtaining statistics for the \" + schemaName + \".\", end=\"\")\n", + "print(tableName + \" table ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.statistics(dbConnection, None, schemaName, tableName, True)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit\n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired\\n.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# As Long As There Are Records (That Were Produced By The ibm_db.statistics API), ...\n", + "noData = False\n", + "loopCounter = 1\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Information Retrieved\n", + " else:\n", + "\n", + " # Display Record Header Information\n", + " print(\"Record number \" + str(loopCounter) + \" details:\")\n", + " print(\"______________________________________________\")\n", + "\n", + " # Display The Information Stored In The Data Record Retrieved\n", + " print(\"Type of data : \", end=\"\")\n", + " if dataRecord['TYPE'] == ibm_db.SQL_TABLE_STAT:\n", + " print(\"Table\")\n", + " elif dataRecord['TYPE'] == ibm_db.SQL_INDEX_CLUSTERED:\n", + " print(\"Clustered index\")\n", + " elif dataRecord['TYPE'] == ibm_db.SQL_INDEX_OTHER:\n", + " print(\"Index\")\n", + " print(\"Table schema : {}\" .format(dataRecord['TABLE_SCHEM']))\n", + " print(\"Table name : {}\" .format(dataRecord['TABLE_NAME']))\n", + " print(\"Index qualifier : {}\" .format(dataRecord['INDEX_QUALIFIER']))\n", + " print(\"Index name : {}\" .format(dataRecord['INDEX_NAME']))\n", + " print(\"Column name : {}\" .format(dataRecord['COLUMN_NAME']))\n", + " print(\"Column position in index : {}\" .format(dataRecord['ORDINAL_POSITION']))\n", + " if not dataRecord['INDEX_NAME'] is None:\n", + " print(\"Index used to enforce uniqueness : \", end=\"\")\n", + " if dataRecord['NON_UNIQUE'] == ibm_db.SQL_FALSE:\n", + " print(\"No\")\n", + " elif dataRecord['NON_UNIQUE'] == ibm_db.SQL_TRUE:\n", + " print(\"Yes\")\n", + " if not dataRecord['INDEX_NAME'] is None:\n", + " print(\"Data order : \", end=\"\")\n", + " if dataRecord['ASC_OR_DESC'] == 'A':\n", + " print(\"Ascending\")\n", + " elif dataRecord['ASC_OR_DESC'] == 'D':\n", + " print(\"Descending\")\n", + " if not dataRecord['INDEX_NAME'] is None:\n", + " print(\"Number of unique values : {}\" .format(dataRecord['CARDINALITY']))\n", + " else:\n", + " print(\"Number of rows (records) : {}\" .format(dataRecord['CARDINALITY']))\n", + "\n", + " print(\"Number of pages used : {}\" .format(dataRecord['PAGES']))\n", + "\n", + " # Increment The loopCounter Variable And Print A Blank Line To Separate The\n", + " # Records From Each Other\n", + " loopCounter += 1\n", + " print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-stmt_error.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-stmt_error.ipynb new file mode 100644 index 0000000..b1598a6 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-stmt_error.ipynb @@ -0,0 +1,295 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.stmt_error()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Return an SQLSTATE value associated with an `IBM_DBStatement` object." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax: " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`string ibm_db.stmt_error( [ IBM_DBStatement `*`statement`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return Values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*statement*__ value is provided: \n", + "* If there is an __error__ associated with the `IBM_DBStatement` object specified, a string containing an SQLSTATE value that explains why the last operation using the `IBM_DBStatement` object failed.\n", + "* If there is __no error__ associated with the `IBM_DBStatement` object specified, an empty string (`''`)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*statement*__ value is not provided: \n", + "* If there is an __error__ associated with the last attempt to return an `IBM_DBStatement` object from an __ibm_db.prepare()__, __ibm_db.exec_immediate()__, or __ibm_db.callproc()__ API, a string containing an SQLSTATE value that explains why the API failed.\n", + "* If there is __no error__ associated with the last attempt to return an `IBM_DBStatement` object, an empty string (`''`)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.stmt_error()__ API can be used to return an SQLSTATE value that explains why an attempt to return an `IBM_DBStatement` object from an __ibm_db.prepare()__, __ibm_db.exec_immediate()__, or __ibm_db.callproc()__ API call was not successful. It can also be used to return an SQLSTATE value that identifies why the last operation using a `IBM_DBStatement` object failed." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Executing the SQL statement specified ... \n", + "ERROR: Unable to execute the SQL statement.\n", + "\n", + "SQLSTATE: 42617\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + }, + { + "ename": "ipynb_Exit", + "evalue": "", + "output_type": "error", + "traceback": [ + "An exception has occurred, use %tb to see the full traceback.\n", + "\u001b[0;31mipynb_Exit\u001b[0m\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-stmt_error.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.stmt_error() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.exec_immediate() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "sqlStatement = \" \" # An Empty SQL Statement Is Used To Force An Error To Occur\n", + "resultSet = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Execute The SQL Statement Specified\n", + "print(\"Executing the SQL statement specified ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit \n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to execute the SQL statement.\")\n", + " errorCode = ibm_db.stmt_error()\n", + " print(\"\\nSQLSTATE: \"+ errorCode + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-stmt_errormsg.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-stmt_errormsg.ipynb new file mode 100644 index 0000000..038e548 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-stmt_errormsg.ipynb @@ -0,0 +1,295 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.stmt_errormsg()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Return an SQLCODE and corresponding error message associated with an `IBM_DBStatement` object." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`string ibm_db.stmt_errormsg( [ IBM_DBStatement `*`statement`*`] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*statement*__    : A valid `IBM_DBStatement` object." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*statement*__ value is provided: \n", + "* If there is an __error__ associated with the `IBM_DBStatement` object specified, a string containing an SQLCODE and corresponding error message that explains why the last operation using the `IBM_DBStatement` object failed.\n", + "* If there is __no error__ associated with the `IBM_DBStatement` object specified, an empty string (`''`)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "When a __*statement*__ value is not provided: \n", + "* If there is an __error__ associated with the last attempt to return an `IBM_DBStatement` object from an __ibm_db.prepare()__, __ibm_db.exec_immediate()__, or __ibm_db.callproc()__ API, a string containing an SQLCODE and corresponding error message that explains why the API failed.\n", + "* If there is __no error__ associated with the last attempt to return an `IBM_DBStatement` object, an empty string (`''`)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.stmt_errormsg()__ API can be used to return an SQLCODE and corresponding error message that explains why an attempt to return an `IBM_DBStatement` object from an __ibm_db.prepare()__, __ibm_db.exec_immediate()__, or __ibm_db.callproc()__ API call was not successful. It can also be used to return an SQLCODE and error message that identifies why the last operation using a `IBM_DBStatement` object failed." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Preparing the SQL statement specified for execution ... \n", + "ERROR: Unable to prepare the SQL statement specified.\n", + "\n", + "[IBM][CLI Driver][DB2/LINUXX8664] SQL0198N The statement string of the PREPARE or EXECUTE IMMEDIATE statement is blank or empty. SQLSTATE=42617 SQLCODE=-198\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + }, + { + "ename": "ipynb_Exit", + "evalue": "", + "output_type": "error", + "traceback": [ + "An exception has occurred, use %tb to see the full traceback.\n", + "\u001b[0;31mipynb_Exit\u001b[0m\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-stmt_errormsg.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.stmt_errormsg() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.prepare() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "sqlStatement = \" \" # An Empty SQL Statement Is Used To Force An Error To Occur\n", + "preparedStmt = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Prepare The SQL Statement Specified\n", + "print(\"Preparing the SQL statement specified for execution ... \", end=\"\")\n", + "try:\n", + " preparedStmt = ibm_db.prepare(dbConnection, sqlStatement)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If Db2 Could Not Parse And Prepare The SQL Statement Correctly, Display An Error Message\n", + "# And Exit\n", + "if preparedStmt is False:\n", + " print(\"\\nERROR: Unable to prepare the SQL statement specified.\")\n", + " errorMsg = ibm_db.stmt_errormsg()\n", + " print(\"\\n\" + errorMsg + \"\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-table_privileges.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-table_privileges.ipynb new file mode 100644 index 0000000..523a94c --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-table_privileges.ipynb @@ -0,0 +1,394 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.table_privileges()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "Retrieve a list of tables and their associated privileges." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.table_privileges( IBM_DBConnection `*`connection`*` [, string `*`qualifierName`*
` [, string `*`schemaName`*` [, string `*`tableName`*`] ] ] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__        : A valid Db2 server or database connection. \n", + "* __qualifierName__    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value `None` or an empty string (`''`) for Db2 databases on other operating systems. \n", + "* __schemaName__     : The name of the schema that contains the table(s) that information is to be obtained for. To match all schemas, provide the value `None` or an empty string; to match select schemas, provide a search pattern that contains __`_`__ and/or __`%`__ wildcards.\n", + "* __tableName__          : The name of the table(s) that information is to be obtained for. To match all tables, provide the value `None` or an empty string; to match select tables, provide a search pattern that contains __`_`__ and/or __`%`__ wildcards. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an IBM_DBStatement with a result set that contains the following information:

\n", + "\n", + " * `TABLE_CAT`        : The name of the catalog associated with the schema and table the table privilege is for; Db2 does not use catalogs so this field will always contain the value `None`. *(Db2 databases on OS/390 or z/OS servers can return information in this field.)*\n", + " * `TABLE_SCHEM`    : The name of the schema for the table the privilege is associated with.\n", + " * `TABLE_NAME`      : The name of the table the privilege is associated with.\n", + " * `PRIVILEGE`        : The table privilege. Valid values are `ALTER`, `CONTROL`, `DELETE`, `INDEX`, `INSERT`, `REFERENCES`, `SELECT`, and `UPDATE`.\n", + " * `GRANTOR`            : The authorization ID of the user who granted the privilege.\n", + " * `GRANTEE`            : The authorization ID of the user to whom the privilege was granted.\n", + " * `IS_GRANTABLE`  : Indication of whether the authorization ID of the user to whom the privilege was granted (the __GRANTEE__) is permitted to grant the privilege to others. Valid values are `YES` and `NO`.

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.table_privileges()__ API is used to retrieve a list of tables and the privileges associated with them.

\n", + "\n", + "The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Obtaining information about privileges that exist for the DB2INST1.PROJECT table ... Done!\n", + "\n", + "Table privilege 1 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : ALTER\n", + "Privilege is grantable : YES\n", + "\n", + "Table privilege 2 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : CONTROL\n", + "Privilege is grantable : NO\n", + "\n", + "Table privilege 3 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : DELETE\n", + "Privilege is grantable : YES\n", + "\n", + "Table privilege 4 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : INDEX\n", + "Privilege is grantable : YES\n", + "\n", + "Table privilege 5 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : INSERT\n", + "Privilege is grantable : YES\n", + "\n", + "Table privilege 6 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : REFERENCES\n", + "Privilege is grantable : YES\n", + "\n", + "Table privilege 7 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : SELECT\n", + "Privilege is grantable : YES\n", + "\n", + "Table privilege 8 details:\n", + "___________________________________\n", + "Schema name : DB2INST1\n", + "Table name : PROJECT\n", + "Privilege grantor : SYSIBM\n", + "Privilege recipient : DB2INST1\n", + "Privilege : UPDATE\n", + "Privilege is grantable : YES\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-table_privileges.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.table_privileges() #\n", + "# API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.fetch_assoc() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "schemaName = userID.upper()\n", + "tableName = \"PROJECT\"\n", + "resultSet = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Retrieve Information About All Of The Privileges That Have Been Defined For The\n", + "# Table Specified\n", + "print(\"Obtaining information about privileges that exist for the \", end=\"\")\n", + "print(schemaName + \".\" + tableName + \" table ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.table_privileges(dbConnection, None, schemaName, tableName)\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit\n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired.\\n\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# As Long As There Are Records (That Were Produced By The ibm_db.table_privileges API), ...\n", + "noData = False\n", + "loopCounter = 1\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Information Retrieved\n", + " else:\n", + "\n", + " # Display Record Header Information\n", + " print(\"Table privilege \" + str(loopCounter) + \" details:\")\n", + " print(\"___________________________________\")\n", + "\n", + " # Display The Information Stored In The Data Record Retrieved\n", + " print(\"Schema name : {}\" .format(dataRecord['TABLE_SCHEM']))\n", + " print(\"Table name : {}\" .format(dataRecord['TABLE_NAME']))\n", + " print(\"Privilege grantor : {}\" .format(dataRecord['GRANTOR']))\n", + " print(\"Privilege recipient : {}\" .format(dataRecord['GRANTEE']))\n", + " print(\"Privilege : {}\" .format(dataRecord['PRIVILEGE']))\n", + " print(\"Privilege is grantable : {}\" .format(dataRecord['IS_GRANTABLE']))\n", + "\n", + " # Increment The loopCounter Variable And Print A Blank Line To Separate The\n", + " # Records From Each Other\n", + " loopCounter += 1\n", + " print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db-tables.ipynb b/python_samples/Jupyter_Notebooks/ibm_db-tables.ipynb new file mode 100644 index 0000000..e9994a6 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db-tables.ipynb @@ -0,0 +1,339 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "# ibm_db.tables()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Purpose:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Retrieve a list of tables and their associated metadata. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Syntax:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "`IBM_DBStatement ibm_db.tables( IBM_DBConnection `*`connection`*` [, string `*`qualifierName`*` [, string `*`schemaName`*` [, string `*`tableName`*` [, string `*`tableType`*`] ] ] ] )`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Parameters:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* __*connection*__        : A valid Db2 server or database connection. \n", + "* __qualifierName__    : A valid qualifier name for Db2 databases on OS/390 or z/OS servers; the value `None` or an empty string (`''`) for Db2 databases on other operating systems. \n", + "* __schemaName__     : The name of the schema that contains the table(s) that information is to be obtained for. To match all schemas, provide the value `None` or an empty string; to match select schemas, provide a search pattern that contains __`_`__ and/or __`%`__ wildcards.\n", + "* __tableName__          : The name of the table(s) that information is to be obtained for. To match all tables, provide the value `None` or an empty string; to match select tables, provide a search pattern that contains __`_`__ and/or __`%`__ wildcards. \n", + "* __tableType__           : The type(s) of table(s) that information is to be obtained for. To match all table types, provide the value `None` or an empty string; to match specific table type(s), provide one or more of the following values (use a comma delimiter to separate values):

\n", + " \n", + " * `'ALIAS'`                                           : Obtain information for aliases.\n", + " * `'TABLE'`                                           : Obtain information for tables. \n", + " * `'TYPED TABLE'`                               : Obtain information for typed tables.\n", + " * `'SYSTEM TABLE'`                             : Obtain information for system catalog tables.\n", + " * `'HIERARCHY TABLE'`                       : Obtain information for hierarchy tables.\n", + " * `'MATERIALIZED QUERY TABLE'`     : Obtain information for materialized query tables (MQTs) tables.\n", + " * `'VIEW'`                                             : Obtain information for views.\n", + " * `'TYPED VIEW'`                                 : Obtain information for typed views.\n", + " * `'INOPERATIVE VIEW'`                     : Obtain information for inoperative views.\n", + " * `'NICKNAME'`                                     : Obtain information for nicknames." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Return values:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "* If __successful__, an IBM_DBStatement with a result set that contains the following information:

\n", + "\n", + " * `TABLE_CAT`        : The name of the catalog associated with the schema and table; Db2 does not use catalogs so this field will always contain the value `None`. *(Db2 databases on OS/390 or z/OS servers can return information in this field.)*\n", + " * `TABLE_SCHEM`    : The name of the schema that contains the table.\n", + " * `TABLE_NAME`      : The name of the table.\n", + " * `TABLE_TYPE`      : The type identifier for the table. (Refer to the __*tableType*__ parameter for a list of the table type identifiers available.)\n", + " * `REMARKS`            : A user-supplied description of the table (if one has been provided).

\n", + " \n", + "* If __unsuccessful__, the value `False`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Description:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "The __ibm_db.tables()__ API is used to retrieve a list of tables and all associated metadata, for one or more table types.

\n", + "\n", + "The information returned by this API is placed in a result data set, which can be processed using the same APIs that are used to process result data sets that are generated by SQL queries. That is, a single row can be retrieved and stored in a tuple or dictionary using the __ibm_db.fetch_tuple()__ (tuple), __ibm_db.fetch_assoc()__ (dictionary), or __ibm_db.fetch_both()__ (tuple *and* dictionary) APIs. Alternately, the __ibm_db.fetch_row()__ API can be used to move the result set pointer to each row in the result set produced and the __ibm_db.result()__ API can be used to fetch a column from the current row." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": false, + "editable": false + }, + "source": [ + "## Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "deletable": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Connecting to the SAMPLE database ... Done!\n", + "\n", + "Obtaining information about select tables in the DB2INST1 schema ... Done!\n", + "\n", + "Table 1 details:\n", + "________________________\n", + "Table schema : DB2INST1\n", + "Table name : PROJACT\n", + "Table type : TABLE\n", + "Description : None\n", + "\n", + "Table 2 details:\n", + "________________________\n", + "Table schema : DB2INST1\n", + "Table name : PROJECT\n", + "Table type : TABLE\n", + "Description : None\n", + "\n", + "Disconnecting from the SAMPLE database ... Done!\n", + "\n" + ] + } + ], + "source": [ + "#----------------------------------------------------------------------------------------------#\n", + "# NAME: ibm_db-tables.py #\n", + "# #\n", + "# PURPOSE: This program is designed to illustrate how to use the ibm_db.tables() API. #\n", + "# #\n", + "# Additional APIs used: #\n", + "# ibm_db.fetch_assoc() #\n", + "# #\n", + "#----------------------------------------------------------------------------------------------#\n", + "# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY #\n", + "# #\n", + "# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved #\n", + "# Licensed Materials - Property of IBM #\n", + "# #\n", + "# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA #\n", + "# ADP Schedule Contract with IBM Corp. #\n", + "# #\n", + "# The following source code (\"Sample\") is owned by International Business Machines #\n", + "# Corporation (\"IBM\") or one of its subsidiaries and is copyrighted and licensed, not sold. #\n", + "# You may use, copy, modify, and distribute the Sample in any form without payment to IBM, #\n", + "# for the purpose of assisting you in the creation of Python applications using the ibm_db #\n", + "# library. #\n", + "# #\n", + "# The Sample code is provided to you on an \"AS IS\" basis, without warranty of any kind. IBM #\n", + "# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT #\n", + "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #\n", + "# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so #\n", + "# the above limitations or exclusions may not apply to you. IBM shall not be liable for any #\n", + "# damages you suffer as a result of using, copying, modifying or distributing the Sample, #\n", + "# even if IBM has been advised of the possibility of such damages. #\n", + "#----------------------------------------------------------------------------------------------#\n", + "\n", + "# Load The Appropriate Python Modules\n", + "import sys # Provides Information About Python Interpreter Constants And Functions\n", + "import ibm_db # Contains The APIs Needed To Work With Db2 Databases\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined #\n", + "# In The File Named \"ibm_db_tools.py\"; This Class Contains The Programming Logic Needed To #\n", + "# Establish And Terminate A Connection To A Db2 Server Or Database #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ibm_db_tools import Db2ConnectionMgr\n", + "\n", + "#----------------------------------------------------------------------------------------------#\n", + "# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In #\n", + "# The File Named \"ipynb_exit.py\"; This Class Contains The Programming Logic Needed To Allow #\n", + "# \"exit()\" Functionality To Work Without Raising An Error Or Stopping The Kernel If The #\n", + "# Application Is Invoked In A Jupyter Notebook #\n", + "#----------------------------------------------------------------------------------------------#\n", + "from ipynb_exit import exit\n", + "\n", + "# Define And Initialize The Appropriate Variables\n", + "dbName = \"SAMPLE\"\n", + "userID = \"db2inst1\"\n", + "passWord = \"Passw0rd\"\n", + "dbConnection = None\n", + "schemaName = userID.upper()\n", + "resultSet = False\n", + "dataRecord = False\n", + "\n", + "# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database\n", + "conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)\n", + "conn.openConnection()\n", + "if conn.returnCode is True:\n", + " dbConnection = conn.connectionID\n", + "else:\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Attempt To Retrieve Information About The Tables In The Current User's Schema Whose Name\n", + "# Begins With The Letter \"P\"\n", + "print(\"Obtaining information about select tables in the \", end=\"\")\n", + "print(schemaName + \" schema ... \", end=\"\")\n", + "try:\n", + " resultSet = ibm_db.tables(dbConnection, None, schemaName, 'P%', 'TABLE')\n", + "except Exception:\n", + " pass\n", + "\n", + "# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit\n", + "if resultSet is False:\n", + " print(\"\\nERROR: Unable to obtain the information desired\\n.\")\n", + " conn.closeConnection()\n", + " exit(-1)\n", + "\n", + "# Otherwise, Complete The Status Message\n", + "else:\n", + " print(\"Done!\\n\")\n", + "\n", + "# As Long As There Are Records (That Were Produced By The ibm_db.tables API), ...\n", + "noData = False\n", + "loopCounter = 1\n", + "while noData is False:\n", + "\n", + " # Retrieve A Record And Store It In A Python Dictionary\n", + " try:\n", + " dataRecord = ibm_db.fetch_assoc(resultSet)\n", + " except:\n", + " pass\n", + "\n", + " # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The\n", + " # \"No Data\" Flag And Exit The Loop \n", + " if dataRecord is False:\n", + " noData = True\n", + "\n", + " # Otherwise, Display The Information Retrieved\n", + " else:\n", + "\n", + " # Display Record Header Information\n", + " print(\"Table \" + str(loopCounter) + \" details:\")\n", + " print(\"________________________\")\n", + "\n", + " # Display The Information Stored In The Data Record Retrieved\n", + " print(\"Table schema : {}\" .format(dataRecord['TABLE_SCHEM']))\n", + " print(\"Table name : {}\" .format(dataRecord['TABLE_NAME']))\n", + " print(\"Table type : {}\" .format(dataRecord['TABLE_TYPE']))\n", + " print(\"Description : {}\" .format(dataRecord['REMARKS']))\n", + "\n", + " # Increment The loopCounter Variable And Print A Blank Line To Separate The\n", + " # Records From Each Other\n", + " loopCounter += 1\n", + " print()\n", + "\n", + "# Close The Database Connection That Was Opened Earlier\n", + "conn.closeConnection()\n", + "\n", + "# Return Control To The Operating System\n", + "exit()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python_samples/Jupyter_Notebooks/ibm_db_tools.py b/python_samples/Jupyter_Notebooks/ibm_db_tools.py new file mode 100644 index 0000000..b524a45 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ibm_db_tools.py @@ -0,0 +1,360 @@ +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_tools.py # +# # +# PURPOSE: This file contains classes and functions that are used by many of the ibm_db sample # +# programs and Jupyter Notebooks. # +# # +# APIs used: # +# ibm_db.connect() # +# ibm_db.conn_errormsg() # +# ibm_db.close() # +# ibm_db.exec_immediate() # +# ibm_db.fetch_tuple() # +# # +# USAGE: Add the following lines of code at the beginning of an ibm_db sample program: # +# # +# from ibm_db_tools import Db2ConnectionMgr # +# from ibm_db_tools import get_row_count # +# from ibm_db_tools import query_sdb_dir (Use with Python sample programs only) # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose of # +# assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import subprocess # Required To Execute A Shell Command +import socket # Provides Access To The BSD Low-Level Networking Interface +import string # Privides APIs Needed To Work With Strings +from io import StringIO # Implements A File-Like Class That Reads And Writes A String + # Buffer (i.e., A Memory File) +from IPython import get_ipython # Simple Function To Call To Get The Current Interactive Shell + # Instance +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# CLASS NAME: Db2ConnectionMgr() # +# PURPOSE: This class contains attributes and methods that can be used to establish and # +# terminate a connection to a Db2 server or database. # +#-------------------------------------------------------------------------------------------------# +class Db2ConnectionMgr(): + """A simple class that manages a Db2 server or database connection.""" + + #---------------------------------------------------------------------------------------------# + # FUNCTION NAME: __init()__ # + # PURPOSE: This method initializes all attributes used by an instance of the # + # Db2ConnectionMgr class. # + # PARAMETERS: dbName - Db2 server or database name # + # dsType - Db2 server or database type ('DB' or 'SERVER') # + # hostName - Db2 server host name or IP address # + # portNum - Port number Db2 uses at the specified server # + # userID - User authentication ID # + # passWord - User password # + #---------------------------------------------------------------------------------------------# + def __init__(self, dsType='', dbName=None, hostName='', portNum='', + userID=None, passWord=None): + """Initialize Db2 server or database name, user ID, and password attributes.""" + + self.dsType = dsType + self.dbName = dbName + self.hostName = hostName + self.portNum = portNum + self.userID = userID + self.passWord = passWord + self.connectionID = None + self.returnCode = False + + # If A Data Source Type Was Not Specified, Use 'DB' By Default + if self.dsType is '': + self.dsType = 'DB' + + #---------------------------------------------------------------------------------------------# + # FUNCTION NAME: openConnection() # + # PURPOSE: This method attempts to open the Db2 server or database connection # + # specified. # + # PARAMETERS: None # + #---------------------------------------------------------------------------------------------# + def openConnection(self): + """Attempt to establish a Db2 server or database connection.""" + + # Define And Initialize The Appropriate Local Variables + connString = "DRIVER={IBM DB2 ODBC DRIVER}" + msgString = "" + + # If A Host Name Was Not Specified, Use The Name That Is Assigned To The Current Server + if self.hostName is '': + self.hostName = socket.gethostname() + + # If A Port Number Was Not Specified, Use Port Number 50000 + if self.portNum is '': + self.portNum = '50000' + + # Display An Appropriate Status Message And Add The Correct "ATTACH" Value To The + # Connection String Variable (connString) + msgString = "\nConnecting to the " + if self.dsType is 'LOCAL_SVR': + print(msgString + "local server ... ", end="") + if get_ipython(): # If Running With IPython, ... + connString += ";ATTACH=TRUE" # Attach To A Server; Not A Database + else: + connString = "ATTACH=TRUE" # Attach To A Server; Not A Database + elif self.dsType is 'SERVER': + print(msgString + self.hostName + " server ... ", end="") + connString += ";ATTACH=TRUE" # Attach To A Server; Not A Database + else: + print(msgString + self.dbName + " database ... ", end="") + connString += ";ATTACH=FALSE" # Attach To A Database; Not A Server + + # If Appropriate, Construct The Portion Of The Connection String That Will Be Used To + # Establish A Connection To The Local Db2 Server + if self.dsType is 'LOCAL_SVR': + if get_ipython(): # If Running With IPython, ... + connString += ";HOSTNAME=" + socket.gethostname() + connString += ";PORT=" + self.portNum + connString += ";PROTOCOL=TCPIP" + connString += ";UID=" + self.userID + connString += ";PWD=" + self.passWord + + # Otherwise, Construct The Portion Of The Connection String That Will Be Used To + # Establish A Connection To A Remote Db2 Server Or A Db2 Database + else: + connString += ";DATABASE=" + self.dbName # Only Used To Connect To A Database + connString += ";HOSTNAME=" + self.hostName # Only Used To Connect To A Server + connString += ";PORT=" + self.portNum # Only Used To Connect To A Server + connString += ";PROTOCOL=TCPIP" + connString += ";UID=" + self.userID + connString += ";PWD=" + self.passWord + + # Attempt To Establish A Connection To The Appropriate Db2 Server Or Database + # If Running With IPython (i.e., Jupyter Notebook), ... + if get_ipython(): + try: + self.connectionID = ibm_db.connect(connString, '', '') + except Exception: + pass + + # If Running With Python, ... + else: + try: + self.connectionID = ibm_db.connect(connString, self.userID, self.passWord) + except Exception: + pass + + # If A Connection Could Not Be Established, Display An Appropriate Error Message + # And Set The Function Return Code Attribute To "False" + if self.connectionID is None: + msgString = "\nERROR: Unable to connect to the " + if self.dsType is 'LOCAL_SVR': + print(msgString + "local server ... ", end="") + elif self.dsType is 'SERVER': + print(msgString + self.hostName + " server.") + else: + print(msgString + self.dbName + " database.") + msgString = ibm_db.conn_errormsg() + print(msgString + "\n") + print("Connection string used: " + connString + "\n") + self.returnCode = False + + # If A Connection Could Be Established, Complete The Status Message And Set The + # Return Code Attribute To "True" + else: + print("Done!\n") + self.returnCode = True + + #---------------------------------------------------------------------------------------------# + # FUNCTION NAME: closeConnection() # + # PURPOSE: This method attempts to close the specified Db2 server or database # + # connection. # + # PARAMETERS: None # + #---------------------------------------------------------------------------------------------# + def closeConnection(self): + """Attempt to close a Db2 server or database connection.""" + + # Define And Initialize The Appropriate Local Variables + msgString = "" + returnCode = False + + # If A Db2 Server Or Database Connection Exists, ... + if not self.connectionID is None: + + # Display An Appropriate Status Message + msgString = "Disconnecting from the " + if self.dsType is 'LOCAL_SVR': + print(msgString + "local server ... ", end="") + elif self.dsType is 'SERVER': + print(msgString + self.hostName + " server ... ", end="") + else: + print(msgString + self.dbName + " database ... ", end="") + + # Attempt To Close A Db2 Server Or Database Connection That Was Opened Earlier + try: + returnCode = ibm_db.close(self.connectionID) + except Exception: + pass + + # If The Connection Could Not Be Closed, Display An Appropriate Error Message + # And Set The Return Code Attribute To "False" + if returnCode is False: + msgString = "\nERROR: Unable to disconnect from the " + if self.dsType is 'LOCAL_SVR': + print(msgString + "local server.") + elif self.dsType is 'SERVER': + print(msgString + self.hostName + " server.") + else: + print(msgString + self.dbName + " database.") + msgString = ibm_db.conn_errormsg(self.connectionID) + print(msgString + "\n") + self.returnCode = False + + # If The Connection Could Be Closed, Complete The Status Message And Set The + # Return Code Attribute To "True" + else: + print("Done!\n") + self.returnCode = True + + +#-------------------------------------------------------------------------------------------------# +# FUNCTION NAME: get_row_count() # +# PURPOSE: This function queries the Db2 table specified and displays the number of rows # +# (records) found in it. # +# PARAMETERS: dbConnection - A valid Db2 database connection # +# tableName - Name of the table to be queried # +# RETURNS: True - A row count was obtained for the table specified # +# False - A row count could not be obtained for the table specified # +#-------------------------------------------------------------------------------------------------# +def get_row_count(dbConnection, tableName): + + # Define And Initialize The Appropriate Local Variables + resultSet = False + dataRecord = False + + # Create The SQL Statement To Be Executed + sqlStatement = "SELECT COUNT(*) FROM " + tableName + " WITH UR" + + # Execute The SQL Statement Just Defined + try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) + except Exception: + pass + + # If The SQL Statement Could Not Be Executed, Display An Error Message And Return The + # Value "False" + if resultSet is False: + print("\nERROR: Unable to execute the statement specified:") + print(" " + sqlStatement + "\n") + return False + + # Retrieve The Data Produced By The SQL Statement And Store It In A Python Tuple + try: + dataRecord = ibm_db.fetch_tuple(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved, Display An Error Message And Return The Value "False" + if dataRecord is False: + print("\nERROR: Unable to retrieve the data produced by the SQL statement.") + return False + + # If The Data Could Be Retrieved, Display It + else: + print("Number of records found in the " + tableName + " table: ", end="") + print("{}\n" .format(dataRecord[0])) + + # Return The Value "True" To The Calling Function + return True + + +#-------------------------------------------------------------------------------------------------# +# FUNCTION NAME: query_sdb_dir() # +# PURPOSE: This function queries the Db2 System Database Directory and displays the # +# information obtained. # +# PARAMETERS: dbName - Name of the database to retrieve information for # +# RETURNS: True - The Db2 System Database Directory was queried successfully # +# False - Information in Db2 System Database Directory could not be obtained # +#-------------------------------------------------------------------------------------------------# +def query_sdb_dir(dbName): + + # Display An Appropriate Status Message + print("Querying the system database directory ... ", end="") + + # Retrieve The Contents Of The Db2 System Database Directory + result = subprocess.run(['db2', 'LIST DB DIRECTORY'], stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True) + + # If The Contents Of The System Database Directory Could Not Be Retrieved, Display An Error + # Message And Return The Value "False" + if result.returncode > 1: + dirInfo = str("{}".format(result.stdout)) + if not 'SQL1057W' in dirInfo: + print("\nERROR: {}".format(result.stdout)) + else: + print("Done!\n") + print("Information about the " + dbName + " database could not be found.\n") + return False + + # Otherwise, Complete The Status Message And Store The Information Retrieved In A + # String Variable + else: + print("Done!\n") + dirInfo = str("{}".format(result.stdout)) + + # If A Record For The Database Specified Cannot Be Found In Information Obtained, Display + # An Appropriate Message And Return The Value "False" + tempName = dbName + "\n" + if not tempName in dirInfo: + print("Information about the " + dbName + " database could not be found.\n") + return False + + # Otherwise, Extract The Record For The Database Specified From The System Database Directory + # Information Retrieved + else: + + # Display A Report Header + print("System Database Directory") + endingPos = dirInfo.find('Database 1 entry:') + tempStr = dirInfo[30:int(endingPos - 2)] + print(tempStr) + print("__________________________________________________________") + + # Remove All Information Found In The String That Comes Before The Record For The + # Database Specified + dbName = dbName + "\n" + startingPos = dirInfo.find(dbName) + tempStr = dirInfo[int(startingPos - 59):] + + # Remove All Information Found In The String That Comes After The Record For The + # Database Specified + tempStr = tempStr.replace('entry:', 'entry&', 1) + endingPos = tempStr.find('entry:') + endingPos -= 10 + tempStr = tempStr[:endingPos] + tempStr = tempStr.replace('entry&', 'entry:', 1) + endingPos -= 1 + while not tempStr[endingPos] is '\n': + endingPos -= 1 + dirInfo = tempStr[:endingPos] + + # Display The Record That Was Obtained For The Database Specified + print(dirInfo + "\n") + + # Return The Value "True" To The Calling Function + return True diff --git a/python_samples/Jupyter_Notebooks/ipynb_exit.py b/python_samples/Jupyter_Notebooks/ipynb_exit.py new file mode 100644 index 0000000..1d647b5 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/ipynb_exit.py @@ -0,0 +1,86 @@ +#-------------------------------------------------------------------------------------------------# +# NAME: ipynb_exit.py # +# # +# PURPOSE: This file contains classes and functions that allows "exit()" functionality to work # +# without raising an error or stopping the kernel when a Python application is # +# invoked from a Jupyter Notebook. # +# # +# USAGE: Add the following line of code to the beginning of a Python program: # +# # +# from ipynb_exit import exit # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose of # +# assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, + # Functions, & Methods +from io import StringIO # Implements A File-Like Class That Reads And Writes A String + # Buffer (i.e., A Memory File) +from IPython import get_ipython # Simple Function To Call To Get The Current Interactive Shell + # Instance + +#-------------------------------------------------------------------------------------------------# +# CLASS NAME: ipynb_Exit() # +# PURPOSE: This class contains attributes and methods that can be used to establish and # +# terminate a connection to a Db2 server or database. # +#-------------------------------------------------------------------------------------------------# +class ipynb_Exit(SystemExit): + """Exit Exception for IPython. Exception temporarily redirects stderr to buffer.""" + + #---------------------------------------------------------------------------------------------# + # FUNCTION NAME: __init()__ # + # PURPOSE: This method initializes an instance of the ipynb_Exit class. # + #---------------------------------------------------------------------------------------------# + def __init__(self): + sys.stderr = StringIO() # Redirect sys.stderr to a StringIO (memory buffer) object. + + #---------------------------------------------------------------------------------------------# + # FUNCTION NAME: __init()__ # + # PURPOSE: This method cleans up when an instance of the ipynb_Exit class is # + # deleted. # + #---------------------------------------------------------------------------------------------# + def __del__(self): + sys.stderr = sys.__stderr__ # Restore sys.stderr to the original values it had at + # the start of the program. + +#-------------------------------------------------------------------------------------------------# +# FUNCTION: customExit() # +# PURPOSE: This function contains attributes and methods that can be used to establish and # +# terminate a connection to a Db2 server or database. # +#-------------------------------------------------------------------------------------------------# +def customExit(returnCode=0): + if returnCode is 0: + ipynb_Exit() + else: + raise ipynb_Exit + +#-------------------------------------------------------------------------------------------------# +# If An Application Running With IPython (i.e., A Jupyter Notebook) Calls The Exit Function, # +# Call A Custom Exit Routine So The Jupyter Notebook Will Not Stop Running; Otherwise, Call The # +# Default Exit Routine # +#-------------------------------------------------------------------------------------------------# +if get_ipython(): + exit = customExit # Rebind To The Custom Exit Function +else: + exit = exit # Just Call The Exit Function diff --git a/python_samples/Jupyter_Notebooks/readme.md b/python_samples/Jupyter_Notebooks/readme.md new file mode 100644 index 0000000..b3b3f80 --- /dev/null +++ b/python_samples/Jupyter_Notebooks/readme.md @@ -0,0 +1,19 @@ +To run these Jupyter Notebooks, perform the following steps: + +

    +
  1. Make sure the permissions for the Anaconda subdirectory are writeable to everyone! (cd to the directory where the Anaconda software was installed and execute the command chmod -R 777)
  2. +
  3. Start Jupyter Notebook and open a new terminal window (New->Terminal)
  4. +
  5. Execute the following commands from the terminal window: +
      +
    • pip install PyHamcrest
    • +
    • pip install --upgrade pip
    • +
    • python -m pip install ibm_db
    • +
    +
  6. Download the following files and copy them to the directory where the Jupyter Notebooks you download will be stored: +
      +
    • ibm_db_tools.py
    • +
    • ipynb_exit.py
    • +
    +
+ +You should now be able to load any of these Jupyter Notebooks and execute the code examples presented in them. diff --git a/python_samples/LICENSE b/python_samples/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/python_samples/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-active.py b/python_samples/Python_Examples/ibm_db/ibm_db-active.py new file mode 100644 index 0000000..c0ebe2c --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-active.py @@ -0,0 +1,87 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-active.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.active() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-active.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +connState = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Determine Whether The Current Database Connection Is Active Or Inactive +try: + connState = ibm_db.active(dbConnection) +except Exception: + pass + +# Display A Status Message That Shows The Current Connection State +print("The connection to the " + dbName + " database is ", end="") +if connState is True: + print("ACTIVE.\n") +elif connState is False: + print("NOT ACTIVE.\n") + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-autocommit.py b/python_samples/Python_Examples/ibm_db/ibm_db-autocommit.py new file mode 100644 index 0000000..bc17848 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-autocommit.py @@ -0,0 +1,151 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-autocommit.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.autocommit() API. # +# # +# Additional APIs used: # +# ibm_db.connect() # +# ibm_db.close() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-autocommit.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +connOption = {ibm_db.SQL_ATTR_AUTOCOMMIT : ibm_db.SQL_AUTOCOMMIT_ON} +dbConnection = None + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + dbConnection = ibm_db.connect(connString, '', '', connOption) +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if dbConnection is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Determine Whether Autocommit Behavior Is OFF or ON (Should Match The connOption Setting) +try: + returnCode = ibm_db.autocommit(dbConnection) +except Exception: + pass + +# If Autocommit Behavior Is OFF, Turn It ON +if returnCode is 0: + print("AUTOCOMMIT behavior is OFF; turning it ON ... ", end="") + try: + returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_ON) + except Exception: + pass + + # If AUTOCOMMIT Behavior Could Not Be Turned ON, Display An Error Message And Continue + if returnCode is False: + print("\nERROR: Unable to turn AUTOCOMMIT behavior ON.") + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# If Autocommit Behavior Is ON, Turn It OFF +elif returnCode is 1: + print("AUTOCOMMIT behavior is ON; turning it OFF ... ", end="") + try: + returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_OFF) + except Exception: + pass + + # If AUTOCOMMIT Behavior Could Not Be Turned OFF, Display An Error Message And Continue + if returnCode is False: + print("\nERROR: Unable to turn AUTOCOMMIT behavior OFF.") + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Check Autocommit Behavior Again And Display Its Status +try: + returnCode = ibm_db.autocommit(dbConnection) +except Exception: + pass + +if returnCode is 0: + print("AUTOCOMMIT behavior is now OFF.\n") +elif returnCode is 1: + print("AUTOCOMMIT behavior is now ON.\n") + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not dbConnection is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = ibm_db.close(dbConnection) + except Exception: + pass + + # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-bind_param.py b/python_samples/Python_Examples/ibm_db/ibm_db-bind_param.py new file mode 100644 index 0000000..7a65fc2 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-bind_param.py @@ -0,0 +1,174 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-bind_param.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.bind_param() API. # +# # +# Additional APIs used: # +# ibm_db.prepare() # +# ibm_db.execute() # +# ibm_db.fetch_tuple() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-bind_param.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +preparedStmt = None +deptID = ['B01', 'C01', 'D01', 'E01'] +returnCode = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed - Include A Parameter Marker +sqlStatement = "SELECT projname FROM project WHERE deptno = ?" + +# Prepare The SQL Statement Just Defined +print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + preparedStmt = ibm_db.prepare(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit +if preparedStmt is False: + print("\nERROR: Unable to prepare the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# For Every Value Specified In The deptID List, ... +for loopCounter in range(0, 4): + + # Display A Message That Identifies The Query Being Executed + print("Processing query " + str(loopCounter + 1) + ":") + + # Assign A Value To The Application Variable That Is To Be Bound To The SQL Statement + paramValue = deptID[loopCounter] + + # Bind The Application Variable To The Parameter Marker Used In The SQL Statement + print(" Binding the appropriate variable to the parameter marker used ... ", end="") + try: + returnCode = ibm_db.bind_param(preparedStmt, 1, paramValue, ibm_db.SQL_PARAM_INPUT, + ibm_db.SQL_CHAR) + except Exception: + pass + + # If The Application Variable Was Not Bound Successfully, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to bind the variable to the parameter marker specified.") + conn.closeConnection() + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!") + + # Execute The Prepared SQL Statement (Using The New Parameter Marker Value) + print(" Executing the prepared SQL statement ", end="") + print("(with the value \'" + paramValue + "\') ... ", end="") + try: + returnCode = ibm_db.execute(preparedStmt) + except Exception: + pass + + # If The SQL Statement Could Not Be Executed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to execute the SQL statement.") + conn.closeConnection() + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!") + + # Display A Report Header + print("Results:\n") + print("DEPTNO PROJNAME") + print("______ _____________________") + + # As Long As There Are Records, ... + noData = False + while noData is False: + + # Retrieve A Record And Store It In A Python Tuple + try: + dataRecord = ibm_db.fetch_tuple(preparedStmt) + except: + pass + + # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The + # "No Data" Flag And Continue + if dataRecord is False: + noData = True + + # Otherwise, Format And Display The Data Retrieved + else: + print("{:<6} {}" .format(paramValue, dataRecord[0])) + + # Add A Blank Line To The End Of The Report + print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-callproc.py b/python_samples/Python_Examples/ibm_db/ibm_db-callproc.py new file mode 100644 index 0000000..dac5246 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-callproc.py @@ -0,0 +1,139 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-callproc.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.callproc() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-callproc.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +spName = "SALARY_STATS" +returnCode = False +spParamValues = (0.0, 0.0, 0.0) +resultSet = None + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Used To Create A New Stored Procedure +sqlStatement = "CREATE OR REPLACE PROCEDURE " + spName +sqlStatement += " (OUT maxSalary DOUBLE, OUT minSalary DOUBLE, OUT avgSalary DOUBLE) " +sqlStatement += "LANGUAGE SQL " +sqlStatement += "DYNAMIC RESULT SETS 0 " +sqlStatement += "READS SQL DATA " +sqlStatement += "NO EXTERNAL ACTION " +sqlStatement += "BEGIN" +sqlStatement += " SELECT MAX(salary) INTO maxSalary FROM employee; " +sqlStatement += " SELECT MIN(salary) INTO minSalary FROM employee; " +sqlStatement += " SELECT AVG(salary) INTO avgSalary FROM employee; " +sqlStatement += "END" + +# Execute The SQL Statement Just Defined +print("Creating an SQL stored procedure named \"" + spName + "\" ... ", end="") +try: + returnCode = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Execute The Stored Procedure Just Created +print("Executing the " + spName + " stored procedure ... ", end="") +try: + resultSet = ibm_db.callproc(dbConnection, spName, spParamValues) +except Exception: + pass + +# If The Stored Procedure Specified Could Not Be Executed, Display An Error Message And Exit +if resultSet is None: + print("\nERROR: Unable to execute the stored procedure specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message; Then Format And Display The Data Values Returned +else: + print("Done!\n") + + # Display A Report Header + print("Salary statistics:") + print("______________________________") + + # Display The Data Values Returned By The Stored Procedure + print("Highest salary : ${:>10.2f}" .format(resultSet[1])) + print("Lowest salary : ${:>10.2f}" .format(resultSet[2])) + print("Average salary : ${:>10.2f}" .format(resultSet[3])) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-client_info.py b/python_samples/Python_Examples/ibm_db/ibm_db-client_info.py new file mode 100644 index 0000000..b01a4f8 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-client_info.py @@ -0,0 +1,108 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-client_info.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.client_info() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-client_info.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +svrConnection = None +clientInfo = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server +conn = Db2ConnectionMgr('SERVER', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + svrConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Obtain Information About The Db2 Client Being Used +print("Obtaining information about the Db2 client ... ", end="") +try: + clientInfo = ibm_db.client_info(svrConnection) +except Exception: + pass + +# If Information About The Client Could Not Be Obtained, Display An Error Message +if clientInfo is False: + print("\nERROR: Unable to obtain Db2 client information.\n") + +# Otherwise, Complete The Status Message; Then Format And Display The Data Retrieved +else: + print("Done!\n") + + # Display A Report Header + print("Client details:") + print("____________________________________________________________________") + + # Display The Client Data + print("Application code page : {}" .format(clientInfo.APPL_CODEPAGE)) + print("Current connection code page : {}" .format(clientInfo.CONN_CODEPAGE)) + print("Data source name (DSN) : {}" .format(clientInfo.DATA_SOURCE_NAME)) + print("Driver name : {}" .format(clientInfo.DRIVER_NAME)) + print("Driver version : {}" .format(clientInfo.DRIVER_VER)) + print("ODBC version supported : {}" .format(clientInfo.DRIVER_ODBC_VER)) + print("ODBC SQL conformance level : ", end="") + if clientInfo.ODBC_SQL_CONFORMANCE == 'MINIMAL': + print("Supports the minimum ODBC SQL grammar\n") + elif clientInfo.ODBC_SQL_CONFORMANCE == 'CORE': + print("Supports the core ODBC SQL grammar\n") + elif clientInfo.ODBC_SQL_CONFORMANCE == 'EXTENDED': + print("Supports extended ODBC SQL grammar\n") + +# Close The Server Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-close.py b/python_samples/Python_Examples/ibm_db/ibm_db-close.py new file mode 100644 index 0000000..3ff798b --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-close.py @@ -0,0 +1,105 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-close.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.close() API. # +# # +# Additional APIs used: # +# ibm_db.connect() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-close.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + dbConnection = ibm_db.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if dbConnection is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + + +# Add Additional Db2 Database-Related Processing Here ... + + +# Attempt To Close The Db2 Database Connection That Was Just Opened +if not dbConnection is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = ibm_db.close(dbConnection) + except Exception: + pass + + # If The Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-column_privileges.py b/python_samples/Python_Examples/ibm_db/ibm_db-column_privileges.py new file mode 100644 index 0000000..e368b9c --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-column_privileges.py @@ -0,0 +1,146 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-column_privileges.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.column_privileges() # +# API. # +# # +# Additional APIs used: # +# ibm_db.fetch_assoc() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-column_privileges.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +schemaName = userID.upper() +tableName = "PROJECT" +columnName = "PROJNO" +resultSet = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Retrieve Information About All Of The Column Privileges That Have Been Defined For +# The Table Specified +print("Obtaining information about column privileges that exist for the " + columnName, end="") +print(" column\nof the " +schemaName + "." + tableName + " table ... ", end="") +try: + resultSet = ibm_db.column_privileges(dbConnection, None, schemaName, tableName, columnName) +except Exception: + pass + +# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to obtain the information desired.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# As Long As There Are Records (That Were Produced By The ibm_db.column_privileges API), ... +noData = False +loopCounter = 1 +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Information Retrieved + else: + + #--------------------------------------------------------------------------------------# + # NOTE: The column name parameter value specified with the ibm_db.column_privileges() # + # API appears to be ignored; if you only want to see column privilege information for # + # a specific column, you will need to use the following filtering code: # + if dataRecord['COLUMN_NAME'] != columnName: + continue + #--------------------------------------------------------------------------------------# + + # Display Record Header Information + print("Column privilege " + str(loopCounter) + " details:") + print("___________________________________") + + # Display The Information Stored In The Data Record Retrieved + print("Schema name : {}" .format(dataRecord['TABLE_SCHEM'])) + print("Table name : {}" .format(dataRecord['TABLE_NAME'])) + print("Column name : {}" .format(dataRecord['COLUMN_NAME'])) + print("Privilege grantor : {}" .format(dataRecord['GRANTOR'])) + print("Privilege recipient : {}" .format(dataRecord['GRANTEE'])) + print("Privilege : {}" .format(dataRecord['PRIVILEGE'])) + print("Privilege is grantable : {}" .format(dataRecord['IS_GRANTABLE'])) + + # Increment The loopCounter Variable And Print A Blank Line To Separate Column The + # Records From Each Other + loopCounter += 1 + print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-columns.py b/python_samples/Python_Examples/ibm_db/ibm_db-columns.py new file mode 100644 index 0000000..83d7c69 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-columns.py @@ -0,0 +1,177 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-columns.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.columns() # +# API. # +# # +# Additional APIs used: # +# ibm_db.fetch_assoc() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-columns.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +tableName = "ACT" +resultSet = False +dataRecord = False +sqlDataTypes = {0 : "SQL_UNKNOWN_TYPE", 1 : "SQL_CHAR", 2 : "SQL_NUMERIC", 3 : "SQL_DECIMAL", + 4 : "SQL_INTEGER", 5 : "SQL_SMALLINT", 6 : "SQL_FLOAT", 7 : "SQL_REAL", 8 : "SQL_DOUBLE", + 9 : "SQL_DATETIME", 12 : "SQL_VARCHAR", 16 : "SQL_BOOLEAN", 19 : "SQL_ROW", + 91 : "SQL_TYPE_DATE", 92 : "SQL_TYPE_TIME", 93 : "SQL_TYPE_TIMESTAMP", + 95 : "SQL_TYPE_TIMESTAMP_WITH_TIMEZONE", -8 : "SQL_WCHAR", -9 : "SQL_WVARCHAR", + -10 : "SQL_WLONGVARCHAR", -95 : "SQL_GRAPHIC", -96 : "SQL_VARGRAPHIC", + -97 : "SQL_LONGVARGRAPHIC", -98 : "SQL_BLOB", -99 : "SQL_CLOB", -350 : "SQL_DBCLOB", + -360 : "SQL_DECFLOAT", -370 : "SQL_XML", -380 : "SQL_CURSORHANDLE", -400 : "SQL_DATALINK", + -450 : "SQL_USER_DEFINED_TYPE"} +sqlDateTimeSubtypes = {1 : "SQL_CODE_DATE", 2 : "SQL_CODE_TIME", 3 : "SQL_CODE_TIMESTAMP", + 4 : "SQL_CODE_TIMESTAMP_WITH_TIMEZONE"} + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Retrieve Information About All Of The Columns That Have Been Defined For +# A Particular Table +print("Obtaining information about columns that have been defined for the ", end="") +print(tableName + " table ... ", end="") +try: + resultSet = ibm_db.columns(dbConnection, None, None, tableName, None) +except Exception: + pass + +# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to obtain the information desired\n.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# As Long As There Are Records (That Were Produced By The ibm_db.columns API), ... +noData = False +loopCounter = 1 +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Information Retrieved + else: + + # Display Record Header Information + print("Column " + str(loopCounter) + " details:") + print("_________________________________________") + + # Display The Information Stored In The Data Record Retrieved + print("Table schema : {}" .format(dataRecord['TABLE_SCHEM'])) + print("Table name : {}" .format(dataRecord['TABLE_NAME'])) + print("Column name : {}" .format(dataRecord['COLUMN_NAME'])) + print("Data type : {}" .format(dataRecord['TYPE_NAME'])) + print("Size : {}" .format(dataRecord['COLUMN_SIZE'])) + print("Buffer size : {}" .format(dataRecord['BUFFER_LENGTH'])) + print("Scale (decimal digits) : ", end="") + if dataRecord['DECIMAL_DIGITS'] == None: + print("Not applicable") + else: + print("{}" .format(dataRecord['DECIMAL_DIGITS'])) + print("Precision radix : ", end="") + if dataRecord['NUM_PREC_RADIX'] == 10: + print("Exact numeric data type") + elif dataRecord['NUM_PREC_RADIX'] == 2: + print("Approximate numeric data type") + elif dataRecord['NUM_PREC_RADIX'] == None: + print("Not applicable") + print("Can accept NULL values : ", end="") + if dataRecord['NULLABLE'] == ibm_db.SQL_FALSE: + print("NO") + elif dataRecord['NULLABLE'] == ibm_db.SQL_TRUE: + print("YES") + print("Remarks : {}" .format(dataRecord['REMARKS'])) + print("Default value : {}" .format(dataRecord['COLUMN_DEF'])) + print("SQL data type : ", end="") + print(sqlDataTypes.get(dataRecord['SQL_DATA_TYPE'])) + print("SQL data/time subtype : ", end="") + print(sqlDateTimeSubtypes.get(dataRecord['SQL_DATETIME_SUB'])) + print("Data type : {}" .format(dataRecord['DATA_TYPE'])) + print("Length in octets : ", end="") + if dataRecord['CHAR_OCTET_LENGTH'] == None: + print("Not applicable") + else: + print("{}" .format(dataRecord['CHAR_OCTET_LENGTH'])) + print("Ordinal position : {}" .format(dataRecord['ORDINAL_POSITION'])) + print("Can contain NULL values : {}" .format(dataRecord['IS_NULLABLE'])) + + # Increment The loopCounter Variable And Print A Blank Line To Separate The + # Records From Each Other + loopCounter += 1 + print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-commit.py b/python_samples/Python_Examples/ibm_db/ibm_db-commit.py new file mode 100644 index 0000000..4502416 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-commit.py @@ -0,0 +1,162 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-commit.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.commit() API. # +# # +# Additional APIs used: # +# ibm_db.autocommit() # +# ibm_db.exec_immediate() # +# ibm_db.stmt_errormsg() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-commit.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The get_row_count() Function That Has Been Defined In The File Named "ibm_db_tools.py"; # +# This Function Contains The Programming Logic Needed To Obtain And Display The Number Of Rows # +# (Records) Found In A Db2 Database Table. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import get_row_count + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +returnCode = False +resultSet = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Turn Autocommit Behavior OFF +print("Turning AUTOCOMMIT behavior OFF ... ", end="") +try: + returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_OFF) +except Exception: + pass + +# If AUTOCOMMIT Behavior Could Not Be Turned OFF, Display An Error Message And Continue +if returnCode is False: + print("\nERROR: Unable to turn AUTOCOMMIT behavior OFF.") + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table +returnCode = get_row_count(dbConnection, 'DEPARTMENT') +if returnCode is False: + conn.closeConnection() + exit(-1) + +# Define The INSERT Statement That Is To Be Used To Add Data To The DEPARTMENT Table +sqlStatement = "INSERT INTO department VALUES('K01', 'SALES', '000130', 'K01', NULL)" + +# Execute The SQL Statement Just Defined +print("Inserting a record into the DEPARTMENT table ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the INSERT statement specified.") + errorMsg = ibm_db.stmt_errormsg() + print("\n" + errorMsg + "\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display The Number Of Rows That Exist In The DEPARTMENT Table Now +# (The Number Returned Should Change) +returnCode = get_row_count(dbConnection, 'DEPARTMENT') +if returnCode is False: + conn.closeConnection() + exit(-1) + +# Commit The Changes Just Made (To Make Them Permanent) +print("Commiting changes made to the database ... ", end="") +resultSet = False +try: + resultSet = ibm_db.commit(dbConnection) +except Exception: + pass + +# If The Commit Operation Could Not Be Performed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to commit the previous operation.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display The Number Of Rows That Exist In The DEPARTMENT Table Now +# (The Number Should Not Change) +returnCode = get_row_count(dbConnection, 'DEPARTMENT') +if returnCode is False: + conn.closeConnection() + exit(-1) + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-conn_error.py b/python_samples/Python_Examples/ibm_db/ibm_db-conn_error.py new file mode 100644 index 0000000..54d424e --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-conn_error.py @@ -0,0 +1,109 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-conn_error.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.conn_error() API. # +# # +# Additional APIs used: # +# ibm_db.connect() # +# ibm_db.close() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-conn_error.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw_rd" # The Wrong Password Is Used To Force An Error To Occur +dbConnection = None + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + dbConnection = ibm_db.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if dbConnection is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + errorCode = ibm_db.conn_error() + print("\nSQLSTATE: "+ errorCode + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + + +# Add Additional Db2 Database-Related Processing Here ... + + +# Attempt To Close The Db2 Database Connection That Was Just Opened +if not dbConnection is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = ibm_db.close(dbConnection) + except Exception: + pass + + # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + errorCode = ibm_db.conn_error(dbConnection) + print("SQLSTATE: "+ errorCode + "\n") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-conn_errormsg.py b/python_samples/Python_Examples/ibm_db/ibm_db-conn_errormsg.py new file mode 100644 index 0000000..c0cbd0e --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-conn_errormsg.py @@ -0,0 +1,109 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-conn_errormsg.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.conn_errormsg() API. # +# # +# Additional APIs used: # +# ibm_db.connect() # +# ibm_db.close() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-conn_errormsg.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw_rd" # The Wrong Password Is Used To Force An Error To Occur +dbConnection = None + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + dbConnection = ibm_db.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if dbConnection is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + errorMsg = ibm_db.conn_errormsg() + print("\n" + errorMsg + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + + +# Add Additional Db2 Database-Related Processing Here ... + + +# Attempt To Close The Db2 Database Connection That Was Just Opened +if not dbConnection is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = ibm_db.close(dbConnection) + except Exception: + pass + + # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + errorMsg = ibm_db.conn_errormsg(dbConnection) + print("\n" + errorMsg + "\n") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-connect_DB.py b/python_samples/Python_Examples/ibm_db/ibm_db-connect_DB.py new file mode 100644 index 0000000..1ca18a0 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-connect_DB.py @@ -0,0 +1,127 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-connect_DB.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.connect() API to # +# establish a connection to a local Db2 database. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# ibm_db.close() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-connect_DB.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connOption = {ibm_db.SQL_ATTR_AUTOCOMMIT: ibm_db.SQL_AUTOCOMMIT_ON} +connectionID = None +resultSet = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db.connect(connString, '', '', connOption, + ibm_db.QUOTED_LITERAL_REPLACEMENT_OFF) +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT deptname FROM org WHERE deptnumb = '50000'" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(connectionID, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + if not connectionID is None: + ibm_db.close(connectionID) + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = ibm_db.close(connectionID) + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-connect_SERVER.py b/python_samples/Python_Examples/ibm_db/ibm_db-connect_SERVER.py new file mode 100644 index 0000000..8013afa --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-connect_SERVER.py @@ -0,0 +1,111 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-connect_SERVER.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.connect() API to # +# establish a connection to a Db2 server. # +# # +# Additional APIs used: # +# ibm_db.close() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-connect_SERVER.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +hostName = "197.126.80.22" # IP Address Of Remote Server +portNum = "50000" # Port Number That Receives Db2 Connections On The Remote Server +userID = "db2inst2" # The Instance User ID At The Remote Server +passWord = "ibmdb2" # The Password For The Instance User ID At The Remote Server +connectionID = None + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Server +# Is About To Be Made +print("\nConnecting to the \'" + hostName + "\' server ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Server Connection +connString = "DRIVER={IBM DB2 ODBC DRIVER}" +connString += ";ATTACH=TRUE" # Attach To A Server; Not A Database +connString += ";DATABASE=" # Ignored When Connecting To A Server +connString += ";HOSTNAME=" + hostName # Required To Connect To A Server +connString += ";PORT=" + portNum # Required To Connect To A Server +connString += ";PROTOCOL=TCPIP" # Required To Connect To A Server +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Server Specified +try: + connectionID = ibm_db.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Server Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + hostName + "\' server.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + + +# Add Additional Db2 Server-Related Processing Here ... +# For Example, ibm_db.createdb(), ibm_db.createdbNX(), ibm_db.recreatedb(), ibm_db.dropdb() + + +# Attempt To Close The Db2 Server Connection That Was Just Opened +if not connectionID is None: + print("Disconnecting from the \'" + hostName + "\' server ... ", end="") + try: + returnCode = ibm_db.close(connectionID) + except Exception: + pass + + # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + hostName + " server.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-createdbNX_LOCAL.py b/python_samples/Python_Examples/ibm_db/ibm_db-createdbNX_LOCAL.py new file mode 100644 index 0000000..3145f7d --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-createdbNX_LOCAL.py @@ -0,0 +1,106 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-createdbNX_LOCAL.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.createdbNX() API to # +# create a local Db2 database without generating an error if that database already # +# exists. # +# # +# Additional APIs used: # +# ibm_db.conn_errormsg() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-createdbNX_LOCAL.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The query_sdb_dir() Function That Has Been Defined In The File Named "ibm_db_tools.py"; # +# This Function Contains The Programming Logic Needed To See If Information About A Specific # +# Database Can Be Found In The Db2 System Database Directory. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import query_sdb_dir + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +userID = "db2inst1" # User ID (Recognized By The Local Server) +passWord = "Passw0rd" # User Password +svrConnection = None +dbName = "MY_DB" +returnCode = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To The Local Db2 Server +conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + svrConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Create A New Database At The Local Server +print("Creating a database named " + dbName + " at the local server. Please wait.") +try: + returnCode = ibm_db.createdbNX(svrConnection, dbName) +except Exception: + pass + +# If The Database Could Not Be Created, Display An Error Message And Exit +if returnCode is False: + print("ERROR: Unable to create the " + dbName + " database.\n") + errorMsg = ibm_db.conn_errormsg(svrConnection) + print(errorMsg + "\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Display A Status Message +else: + print("\nThe database \"" + dbName + "\" has been created!\n") + query_sdb_dir(dbName) + +# Close The Db2 Server Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-createdbNX_REMOTE.py b/python_samples/Python_Examples/ibm_db/ibm_db-createdbNX_REMOTE.py new file mode 100644 index 0000000..1857b26 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-createdbNX_REMOTE.py @@ -0,0 +1,109 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-createdbNX_REMOTE.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.createdbNX() API to # +# create a database on a remote Db2 server without generating an error if that # +# database already exists. # +# # +# Additional APIs used: # +# ibm_db.conn_errormsg() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-createdbNX_REMOTE.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The query_sdb_dir() Function That Has Been Defined In The File Named "ibm_db_tools.py"; # +# This Function Contains The Programming Logic Needed To See If Information About A Specific # +# Database Can Be Found In The Db2 System Database Directory. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import query_sdb_dir + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +hostName = "197.126.80.22" # IP Address Of A Remote Server +portNum = "50000" # Port Number Used By Db2 +userID = "db2inst2" # User ID (Recognized By The Remote Server) +passWord = "ibmdb2" # User Password +svrConnection = None +dbName = "MY_DB" +returnCode = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server +conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord) +conn.openConnection() +if conn.returnCode is True: + svrConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Create A New Database At The Remote Server +print("Creating a database named " + dbName + " at the " + hostName + " server. Please wait.") +try: + returnCode = ibm_db.createdbNX(svrConnection, dbName) +except Exception: + pass + +# If The Database Could Not Be Created, Display An Error Message And Exit +if returnCode is False: + print("ERROR: Unable to create the " + dbName + " database.\n") + errorMsg = ibm_db.conn_errormsg(svrConnection) + print(errorMsg + "\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Display A Status Message And Verify That Information About The Database +# That Was Just Created Exists In The Db2 System Database Directory +else: + print("\nThe database \"" + dbName + "\" has been created!\n") + query_sdb_dir(dbName) + +# Close The Db2 Server Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-createdb_LOCAL.py b/python_samples/Python_Examples/ibm_db/ibm_db-createdb_LOCAL.py new file mode 100644 index 0000000..9d18dcb --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-createdb_LOCAL.py @@ -0,0 +1,105 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-createdb_LOCAL.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.createdb() API to # +# create a database on a local Db2 server. # +# # +# Additional APIs used: # +# ibm_db.conn_errormsg() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-createdb_LOCAL.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The query_sdb_dir() Function That Has Been Defined In The File Named "ibm_db_tools.py"; # +# This Function Contains The Programming Logic Needed To See If Information About A Specific # +# Database Can Be Found In The Db2 System Database Directory. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import query_sdb_dir + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +userID = "db2inst1" # User ID (Recognized By The Local Server) +passWord = "Passw0rd" # User Password +svrConnection = None +dbName = "MY_DB" +returnCode = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To The Local Db2 Server +conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + svrConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Create A New Database At The Local Server +print("Creating a database named " + dbName + " at the local server. Please wait.") +try: + returnCode = ibm_db.createdb(svrConnection, dbName) +except Exception: + pass + +# If The Database Could Not Be Created, Display An Error Message And Exit +if returnCode is False: + print("ERROR: Unable to create the " + dbName + " database.\n") + errorMsg = ibm_db.conn_errormsg(svrConnection) + print(errorMsg + "\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Display A Status Message +else: + print("\nThe database \"" + dbName + "\" has been created!\n") + query_sdb_dir(dbName) + +# Close The Db2 Server Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-createdb_REMOTE.py b/python_samples/Python_Examples/ibm_db/ibm_db-createdb_REMOTE.py new file mode 100644 index 0000000..e0fa852 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-createdb_REMOTE.py @@ -0,0 +1,108 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-createdb_REMOTE.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.createdb() API to # +# create a database on a remote Db2 server. # +# # +# Additional APIs used: # +# ibm_db.conn_errormsg() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-createdb_REMOTE.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The query_sdb_dir() Function That Has Been Defined In The File Named "ibm_db_tools.py"; # +# This Function Contains The Programming Logic Needed To See If Information About A Specific # +# Database Can Be Found In The Db2 System Database Directory. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import query_sdb_dir + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +hostName = "197.126.80.22" # IP Address Of A Remote Server +portNum = "50000" # Port Number Used By Db2 +userID = "db2inst2" # User ID (Recognized By The Remote Server) +passWord = "ibmdb2" # User Password +svrConnection = None +dbName = "MY_DB" +returnCode = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server +conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord) +conn.openConnection() +if conn.returnCode is True: + svrConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Create A New Database At The Remote Server +print("Creating a database named " + dbName + " at the " + hostName + " server. Please wait.") +try: + returnCode = ibm_db.createdb(svrConnection, dbName) +except Exception: + pass + +# If The Database Could Not Be Created, Display An Error Message And Exit +if returnCode is False: + print("ERROR: Unable to create the " + dbName + " database.\n") + errorMsg = ibm_db.conn_errormsg(svrConnection) + print(errorMsg + "\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Display A Status Message And Verify That Information About The Database +# That Was Just Created Exists In The Db2 System Database Directory +else: + print("\nThe database \"" + dbName + "\" has been created!\n") + query_sdb_dir(dbName) + +# Close The Db2 Server Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-cursor_type.py b/python_samples/Python_Examples/ibm_db/ibm_db-cursor_type.py new file mode 100644 index 0000000..4670494 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-cursor_type.py @@ -0,0 +1,189 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-cursor_type.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.cursor_type() API to # +# determine the type of cursor being used. # +# # +# Additional APIs used: # +# ibm_db.set_option() # +# ibm_db.exec_immediate() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-cursor_type.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +cursorType = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT * FROM department" + +# Create A Dictionary That Contains The Value Needed To Specify That A Forward Only Cursor +# Should Be Used +print("Setting cursor type to SQL_CURSOR_FORWARD_ONLY\n") +stmtOption = {ibm_db.SQL_ATTR_CURSOR_TYPE: ibm_db.SQL_CURSOR_FORWARD_ONLY} + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement, stmtOption) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified +print("Obtaining information about the type of cursor being used ... ", end="") +try: + cursorType = ibm_db.cursor_type(resultSet) +except Exception: + pass + +# If Information About The Cursor Could Not Be Obtained, Display An Error Message And Exit +if cursorType is False: + print("\nERROR: Unable to obtain the information desired.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified +print("Type of cursor being used: ", end="") + +if cursorType == ibm_db.SQL_CURSOR_FORWARD_ONLY: + print("Forward only (SQL_CURSOR_FORWARD_ONLY)\n") +elif cursorType == ibm_db.SQL_CURSOR_KEYSET_DRIVEN: + print("Keyset driven (SQL_CURSOR_KEYSET_DRIVEN)\n") +elif cursorType == ibm_db.SQL_CURSOR_DYNAMIC: + print("Dynamic (SQL_CURSOR_DYNAMIC)\n") +elif cursorType == ibm_db.SQL_CURSOR_STATIC: + print("Static (SQL_CURSOR_STATIC)\n") +else: + print("Unknown\n") + +# Create A Dictionary That Contains The Value Needed To Specify That A Keyset-Driven Cursor +# Should Be Used +print("\nSetting cursor type to SQL_CURSOR_KEYSET_DRIVEN\n") +stmtOption = {ibm_db.SQL_ATTR_CURSOR_TYPE: ibm_db.SQL_CURSOR_KEYSET_DRIVEN} + +# Execute The SQL Statement Defined Earlier +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement, stmtOption) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified +print("Obtaining information about the type of cursor being used ... ", end="") +try: + cursorType = ibm_db.cursor_type(resultSet) +except Exception: + pass + +# If Information About The Cursor Could Not Be Obtained, Display An Error Message And Exit +if cursorType is False: + print("\nERROR: Unable to obtain the information desired.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified +print("Type of cursor being used: ", end="") + +if cursorType == ibm_db.SQL_CURSOR_FORWARD_ONLY: + print("Forward only (SQL_CURSOR_FORWARD_ONLY)\n") +elif cursorType == ibm_db.SQL_CURSOR_KEYSET_DRIVEN: + print("Keyset driven (SQL_CURSOR_KEYSET_DRIVEN)\n") +elif cursorType == ibm_db.SQL_CURSOR_DYNAMIC: + print("Dynamic (SQL_CURSOR_DYNAMIC)\n") +elif cursorType == ibm_db.SQL_CURSOR_STATIC: + print("Static (SQL_CURSOR_STATIC)\n") +else: + print("Unknown\n") + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-dropdb_LOCAL.py b/python_samples/Python_Examples/ibm_db/ibm_db-dropdb_LOCAL.py new file mode 100644 index 0000000..577a094 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-dropdb_LOCAL.py @@ -0,0 +1,106 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-dropdb_LOCAL.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.dropdb() API to delete # +# (drop) a local Db2 database. # +# # +# Additional APIs used: # +# ibm_db.conn_errormsg() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-dropdb_REMOTE.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The query_sdb_dir() Function That Has Been Defined In The File Named "ibm_db_tools.py"; # +# This Function Contains The Programming Logic Needed To See If Information About A Specific # +# Database Can Be Found In The Db2 System Database Directory. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import query_sdb_dir + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +userID = "db2inst1" # User ID (Recognized By The Local Server) +passWord = "Passw0rd" # User Password +svrConnection = None +dbName = "MY_DB" +returnCode = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Remote Db2 Server +conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + svrConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Delete (Drop) A Database At The Remote Server +print("Dropping a database named " + dbName + " at the local server. Please wait.") +try: + returnCode = ibm_db.dropdb(svrConnection, dbName) +except Exception: + pass + +# If The Database Could Not Be Deleted, Display An Error Message And Exit +if returnCode is False: + print("ERROR: Unable to drop the " + dbName + " database.\n") + errorMsg = ibm_db.conn_errormsg(svrConnection) + print(errorMsg + "\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Display A Status Message And Verify That Information About The Database +# That Was Just Deleted No Longer Exists In The Db2 System Database Directory +else: + print("\nThe database \"" + dbName + "\" has been deleted!\n") + query_sdb_dir(dbName) + +# Close The Db2 Server Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-dropdb_REMOTE.py b/python_samples/Python_Examples/ibm_db/ibm_db-dropdb_REMOTE.py new file mode 100644 index 0000000..498e504 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-dropdb_REMOTE.py @@ -0,0 +1,108 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-dropdb_REMOTE.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.dropdb() API to delete # +# (drop) a database stored on a remote Db2 server. # +# # +# Additional APIs used: # +# ibm_db.conn_errormsg() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-dropdb_REMOTE.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The query_sdb_dir() Function That Has Been Defined In The File Named "ibm_db_tools.py"; # +# This Function Contains The Programming Logic Needed To See If Information About A Specific # +# Database Can Be Found In The Db2 System Database Directory. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import query_sdb_dir + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +hostName = "197.126.80.22" # IP Address Of A Remote Server +portNum = "50000" # Port Number Used By Db2 +userID = "db2inst2" # User ID (Recognized By The Remote Server) +passWord = "ibmdb2" # User Password +svrConnection = None +dbName = "MY_DB" +returnCode = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Remote Db2 Server +conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord) +conn.openConnection() +if conn.returnCode is True: + svrConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Delete (Drop) A Database At The Remote Server +print("Dropping a database named " + dbName + " at the " + hostName + " server. Please wait.") +try: + returnCode = ibm_db.dropdb(svrConnection, dbName) +except Exception: + pass + +# If The Database Could Not Be Deleted, Display An Error Message And Exit +if returnCode is False: + print("ERROR: Unable to drop the " + dbName + " database.\n") + errorMsg = ibm_db.conn_errormsg(svrConnection) + print(errorMsg + "\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Display A Status Message And Verify That Information About The Database +# That Was Just Deleted No Longer Exists In The Db2 System Database Directory +else: + print("\nThe database \"" + dbName + "\" has been deleted!\n") + query_sdb_dir(dbName) + +# Close The Db2 Server Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-exec_immediate.py b/python_samples/Python_Examples/ibm_db/ibm_db-exec_immediate.py new file mode 100644 index 0000000..873f733 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-exec_immediate.py @@ -0,0 +1,116 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-exec_immediate.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.exec_immediate() API. # +# # +# Additional APIs used: # +# ibm_db.fetch_row() # +# ibm_db.result() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-exec_immediate.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT projno, projname FROM project WHERE prstaff < 2" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("PROJNO PROJNAME") +print("______ _____________________") + +# As Long As There Are Records In The Result Set Produced, ... +while (ibm_db.fetch_row(resultSet) is True): + + # Extract The Data Value For Each Column From The Current Record + projectNum = ibm_db.result(resultSet, 0) + projectName = ibm_db.result(resultSet, 1) + + # Format And Display The Data Retrieved + print("{:6} {:24}" .format(projectNum, projectName)) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-execute.py b/python_samples/Python_Examples/ibm_db/ibm_db-execute.py new file mode 100644 index 0000000..3b3dc09 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-execute.py @@ -0,0 +1,144 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-execute.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.execute() API. # +# # +# Additional APIs used: # +# ibm_db.prepare() # +# ibm_db.fetch_tuple() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-execute.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +preparedStmt = False +returnCode = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT projno, projname FROM project WHERE prstaff < 2" + +# Prepare The SQL Statement Just Defined +print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + preparedStmt = ibm_db.prepare(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit +if preparedStmt is False: + print("\nERROR: Unable to prepare the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Execute The SQL Statement Just Prepared +print("Executing the prepared SQL statement ... ", end="") +try: + returnCode = ibm_db.execute(preparedStmt) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("PROJNO PROJNAME") +print("______ _____________________") + +# As Long As There Are Records In The Result Set Produced, ... +noData = False +while noData is False: + + # Retrieve A Record And Store It In A Python Tuple + try: + dataRecord = ibm_db.fetch_tuple(preparedStmt) + except: + pass + + # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Data Retrieved + else: + print("{:<6} {:24}" .format(dataRecord[0], dataRecord[1])) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-execute_many.py b/python_samples/Python_Examples/ibm_db/ibm_db-execute_many.py new file mode 100644 index 0000000..2cd831a --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-execute_many.py @@ -0,0 +1,141 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-execute_many.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.execute_many() API. # +# # +# Additional APIs used: # +# ibm_db.prepare() # +# ibm_db.fetch_tuple() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-execute_many.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The get_row_count() Function That Has Been Defined In The File Named "ibm_db_tools.py"; # +# This Function Contains The Programming Logic Needed To Obtain And Display The Number Of Rows # +# (Records) Found In A Db2 Database Table. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import get_row_count + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +returnCode = None +preparedStmt = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table +returnCode = get_row_count(dbConnection, 'DEPARTMENT') +if returnCode is False: + conn.closeConnection() + exit(-1) + +# Define The INSERT Statement (With Parameter Markers) That Is To Be Used To Add Data +# To The DEPARTMENT Table +sqlStatement = "INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)" + +# Prepare The SQL Statement Just Defined +print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + preparedStmt = ibm_db.prepare(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit +if preparedStmt is False: + print("\nERROR: Unable to prepare the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Create A List Of Data Values That Are To Be Supplied For The Parameter Markers Coded +# In The INSERT Statement Specified +pmValues = (('K22', 'SALES', '000110'), + ('L22', 'FINANCE', '000120'), + ('M22', 'HUMAN RESOURCES', '000130')) + +# Execute The SQL Statement Just Prepared +print("Executing the prepared SQL statement ... ", end="") +try: + returnCode = ibm_db.execute_many(preparedStmt, pmValues) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if returnCode is True: + print("\nERROR: Unable to execute the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message And Display The Number Of Records Added +else: + print("Done!\n") + print("Number of records added : {}\n" .format(returnCode)) + + # Display The Number Of Rows That Exist In The DEPARTMENT Table Now + # (The Number Returned Should Reflect That Three Rows Were Added) + returnCode = get_row_count(dbConnection, 'DEPARTMENT') + + # Close The Database Connection That Was Opened Earlier + conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-fetch_assoc.py b/python_samples/Python_Examples/ibm_db/ibm_db-fetch_assoc.py new file mode 100644 index 0000000..cd9e1a4 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-fetch_assoc.py @@ -0,0 +1,125 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-fetch_assoc.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.fetch_assoc() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-fetch_assoc.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT deptname FROM department WHERE admrdept = 'A00'" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("DEPTNAME") +print("____________________________") + +# As Long As There Are Records In The Result Set Produced, ... +noData = False +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Data Retrieved + else: + print("{:20}" .format(dataRecord['DEPTNAME'])) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-fetch_both.py b/python_samples/Python_Examples/ibm_db/ibm_db-fetch_both.py new file mode 100644 index 0000000..840b2e3 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-fetch_both.py @@ -0,0 +1,126 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-fetch_both.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.fetch_both() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-fetch_both.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT deptno, deptname FROM department WHERE admrdept = 'A00'" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("DEPTNO DEPTNAME") +print("______ ______________________") + +# As Long As There Are Records In The Result Set Produced, ... +noData = False +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary And A Python Tuple + try: + dataRecord = ibm_db.fetch_both(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Data Retrieved + else: + print("{:6} ".format(dataRecord[0]), end="") # Tuple Value + print("{:20}" .format(dataRecord['DEPTNAME'])) # Dictionary Value + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-fetch_row.py b/python_samples/Python_Examples/ibm_db/ibm_db-fetch_row.py new file mode 100644 index 0000000..82fa653 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-fetch_row.py @@ -0,0 +1,120 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-fetch_row.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.fetch_row() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# ibm_db.result() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-fetch_row.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +dataValue = None + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT deptname FROM department WHERE admrdept = 'A00'" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("DEPTNAME") +print("____________________________") + +# As Long As There Are Records In The Result Set Produced, ... +while (ibm_db.fetch_row(resultSet) is True): + + # Retrieve The Data From The Current Row + try: + dataValue = ibm_db.result(resultSet, 0) + except Exception: + pass + + # Display The Data Retrieved + if not dataValue is None: + print(dataValue) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-fetch_tuple.py b/python_samples/Python_Examples/ibm_db/ibm_db-fetch_tuple.py new file mode 100644 index 0000000..6105ab2 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-fetch_tuple.py @@ -0,0 +1,125 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-fetch_tuple.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.fetch_tuple() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-fetch_tuple.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT deptname FROM department WHERE admrdept = 'A00'" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("DEPTNAME") +print("____________________________") + +# As Long As There Are Records In The Result Set Produced, ... +noData = False +while noData is False: + + # Retrieve A Record And Store It In A Python Tuple + try: + dataRecord = ibm_db.fetch_tuple(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Data Retrieved + else: + print(dataRecord[0]) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-field_display_size.py b/python_samples/Python_Examples/ibm_db/ibm_db-field_display_size.py new file mode 100644 index 0000000..a952eb8 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-field_display_size.py @@ -0,0 +1,140 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-field_display_size.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_display_size() # +# API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# ibm_db.num_fields() # +# ibm_db.field_name() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-field_display_size.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +numColumns = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT * FROM employee" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed +print("Examining the columns returned in the result set produced ... ", end="") +try: + numColumns = ibm_db.num_fields(resultSet) +except Exception: + pass + +# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error +# Message And Exit +if numColumns is False: + print("\nERROR: Unable to obtain information about the result set produced.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Result set information:\n") +print("COLUMN NAME DATA DISPLAY SIZE") +print("___________ _________________") + +# As Long As There Is Column Information, ... +for loopCounter in range(0, numColumns): + + # Get The Name Of The Current Column + colName = ibm_db.field_name(resultSet, loopCounter) + + # Get The Display Size Of The Data For The Current Column + colDispSize = ibm_db.field_display_size(resultSet, loopCounter) + + # Format And Display The Data Retrieved + if (not colName is False) and (not colDispSize is False): + print("{:<13} {:>15}" .format(colName, colDispSize)) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-field_name.py b/python_samples/Python_Examples/ibm_db/ibm_db-field_name.py new file mode 100644 index 0000000..f409fa4 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-field_name.py @@ -0,0 +1,136 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-field_name.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_name() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# ibm_db.num_fields() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-field_name.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +numColumns = False +colName = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT * FROM employee" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed +print("Examining the columns returned in the result set produced ... ", end="") +try: + numColumns = ibm_db.num_fields(resultSet) +except Exception: + pass + +# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error +# Message And Exit +if numColumns is False: + print("\nERROR: Unable to obtain information about the result set produced.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Result set information:\n") +print("COLUMN NUMBER COLUMN NAME") +print("_____________ ___________") + +# As Long As There Is Column Information, ... +for loopCounter in range(0, numColumns): + + # Get The Name Of The Current Column + colName = ibm_db.field_name(resultSet, loopCounter) + + # Format And Display The Data Retrieved + if not colName is False: + print("{:>13} {:<11}" .format(loopCounter, colName)) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-field_num.py b/python_samples/Python_Examples/ibm_db/ibm_db-field_num.py new file mode 100644 index 0000000..07e5250 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-field_num.py @@ -0,0 +1,116 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-field_num.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_num() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-field_num.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +columnNumber = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT * FROM employee" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Find Out Which Column In The Result Set Produced By The Query Just Executed Contains Data +# That Was Retrieved From The "BIRTHDATE" Column Of The Table +try: + columnNumber = ibm_db.field_num(resultSet, 'BIRTHDATE') +except Exception: + pass + +# If The Column Number For The "BIRTHDATE" Column Could Not Be Obtained, Display An Error +# Message And Exit +if columnNumber is False: + print("\nERROR: Unable to obtain information about the result set produced.") + conn.closeConnection() + exit(-1) + +# Format And Display The Data Retrieved +print("\'BIRTHDATE\' data can be found in column number {:<2} " .format(columnNumber), end="") +print("of the result set produced.\n") + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-field_precision.py b/python_samples/Python_Examples/ibm_db/ibm_db-field_precision.py new file mode 100644 index 0000000..159e8c6 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-field_precision.py @@ -0,0 +1,139 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-field_precision.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_precision() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# ibm_db.num_fields() # +# ibm_db.field_name() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-field_precision.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +numColumns = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT salary, bonus, comm FROM employee" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed +print("Examining the columns returned in the result set produced ... ", end="") +try: + numColumns = ibm_db.num_fields(resultSet) +except Exception: + pass + +# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error +# Message And Exit +if numColumns is False: + print("\nERROR: Unable to obtain information about the result set produced.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Result set information:\n") +print("COLUMN NAME PRECISION (TOTAL NUMBER OF DIGITS)") +print("___________ __________________________________") + +# As Long As There Is Column Information, ... +for loopCounter in range(0, numColumns): + + # Get The Name Of The Current Column + colName = ibm_db.field_name(resultSet, loopCounter) + + # Get The Precision Of The Current Column + colPrecision = ibm_db.field_precision(resultSet, loopCounter) + + # Format And Display The Data Retrieved + if (not colName is False) and (not colPrecision is False): + print("{:<13} {:>32}" .format(colName, colPrecision)) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-field_scale.py b/python_samples/Python_Examples/ibm_db/ibm_db-field_scale.py new file mode 100644 index 0000000..8b72f54 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-field_scale.py @@ -0,0 +1,139 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-field_scale.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_scale() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# ibm_db.num_fields() # +# ibm_db.field_name() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-field_scale.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +numColumns = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT salary, bonus, comm FROM employee" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed +print("Examining the columns returned in the result set produced ... ", end="") +try: + numColumns = ibm_db.num_fields(resultSet) +except Exception: + pass + +# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error +# Message And Exit +if numColumns is False: + print("\nERROR: Unable to obtain information about the result set produced.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Result set information:\n") +print("COLUMN NAME SCALE (DECIMAL DIGITS)") +print("___________ ______________________") + +# As Long As There Is Column Information, ... +for loopCounter in range(0, numColumns): + + # Get The Name Of The Current Column + colName = ibm_db.field_name(resultSet, loopCounter) + + # Get The Scale Of The Current Column + colScale = ibm_db.field_scale(resultSet, loopCounter) + + # Format And Display The Data Retrieved + if (not colName is False) and (not colScale is False): + print("{:<13} {:>20}" .format(colName, colScale)) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-field_type.py b/python_samples/Python_Examples/ibm_db/ibm_db-field_type.py new file mode 100644 index 0000000..c747352 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-field_type.py @@ -0,0 +1,139 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-field_type.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_type() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# ibm_db.num_fields() # +# ibm_db.field_name() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-field_type.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +numColumns = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT * FROM employee" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed +print("Examining the columns returned in the result set produced ... ", end="") +try: + numColumns = ibm_db.num_fields(resultSet) +except Exception: + pass + +# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error +# Message And Exit +if numColumns is False: + print("\nERROR: Unable to obtain information about the result set produced.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Result set information:\n") +print("COLUMN NAME DATA TYPE") +print("___________ _________") + +# As Long As There Is Column Information, ... +for loopCounter in range(0, numColumns): + + # Get The Name Of The Current Column + colName = ibm_db.field_name(resultSet, loopCounter) + + # Get The Data Type Of The Current Column + colDataType = ibm_db.field_type(resultSet, loopCounter) + + # Format And Display The Data Retrieved - Show Data Types In Upper Case + if (not colName is False) and (not colDataType is False): + print("{:<13} {:>7}" .format(colName, colDataType.upper())) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-field_width.py b/python_samples/Python_Examples/ibm_db/ibm_db-field_width.py new file mode 100644 index 0000000..f2178da --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-field_width.py @@ -0,0 +1,139 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-field_width.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.field_width() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# ibm_db.num_fields() # +# ibm_db.field_name() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-field_width.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +numColumns = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT * FROM emp_resume" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed +print("Examining the columns returned in the result set produced ... ", end="") +try: + numColumns = ibm_db.num_fields(resultSet) +except Exception: + pass + +# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error +# Message And Exit +if numColumns is False: + print("\nERROR: Unable to obtain information about the result set produced.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Result set information:\n") +print("COLUMN NAME MAXIMUM VALUE SIZE (IN BYTES)") +print("_____________ _____________________________") + +# As Long As There Is Column Information, ... +for loopCounter in range(0, numColumns): + + # Get The Name Of The Current Column + colName = ibm_db.field_name(resultSet, loopCounter) + + # Get The Size Of The Data Allowed In The Current Column + colWidth = ibm_db.field_width(resultSet, loopCounter) + + # Format And Display The Data Retrieved + if (not colName is False) and (not colWidth is False): + print("{:<13} {:>29}" .format(colName, colWidth)) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-foreign_keys.py b/python_samples/Python_Examples/ibm_db/ibm_db-foreign_keys.py new file mode 100644 index 0000000..e392da4 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-foreign_keys.py @@ -0,0 +1,192 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-foreign_keys.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.foreign_keys() API. # +# # +# Additional APIs used: # +# ibm_db.tables() # +# ibm_db.fetch_assoc() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-foreign_keys.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +schemaName = userID.upper() +tableName = "PROJECT" +resultSet = False +dataRecord = False +foreignKeyRules = {0 : "CASCADE", 1 : "RESTRICT", 2 : "SET_NULL", 3 : "NO_ACTION", + 4 : "SET_DEFAULT"} +deferability = {5 : "INITIALLY_DEFERRED", 6 : "INITIALLY_IMMEDIATE", + 7 : "NOT_DEFERRABLE"} + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Retrieve Information About All Of The Tables In The Current User's Schema +print("Obtaining information about tables in the " + schemaName + " schema ... ", end="") +try: + resultSet = ibm_db.tables(dbConnection, None, schemaName, None, 'TABLE') +except Exception: + pass + +# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to obtain the information desired\n.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# As Long As There Are Records (That Were Produced By The ibm_db.tables API), ... +tableList = [] +noData = False +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Store The Table Name Retrieved In A Python List (This List Will Be Used + # Later To Skip Records Associated With Aliases) + else: + tableList.append(dataRecord['TABLE_NAME']) + +# Attempt To Retrieve Information About All Of The Foreign Keys That Have Been Defined For +# The Table Specified +print("Obtaining information about foreign keys created for ", end="") +print("the " + schemaName + "." + tableName + " table ... ", end="") +resultSet = False +try: + resultSet = ibm_db.foreign_keys(dbConnection, None, schemaName, tableName) +except Exception: + pass + +# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to obtain the information desired\n.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# As Long As There Are Records (That Were Produced By The ibm_db.foreign_keys API), ... +noData = False +loopCounter = 1 +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Data Retrieved (Skip Information For Aliases) + else: + + # If The Current Data Record Is For A Table Alias, Ignore It + if not dataRecord['FKTABLE_NAME'] in tableList: + continue + + # Display Record Header Information + print("Foreign key " + str(loopCounter) + " details:") + print("______________________________________________") + + # Display The Information Stored In The Data Record Retrieved + print("Primary key name : {}" .format(dataRecord['PK_NAME'])) + print(" Table schema : {}" .format(dataRecord['PKTABLE_SCHEM'])) + print(" Table name : {}" .format(dataRecord['PKTABLE_NAME'])) + print(" Column name : {}" .format(dataRecord['PKCOLUMN_NAME'])) + print("Foreign key name : {}" .format(dataRecord['FK_NAME'])) + print(" Table schema : {}" .format(dataRecord['FKTABLE_SCHEM'])) + print(" Table name : {}" .format(dataRecord['FKTABLE_NAME'])) + print(" Column name : {}" .format(dataRecord['FKCOLUMN_NAME'])) + print(" Column number : {}" .format(dataRecord['KEY_SEQ'])) + print(" UPDATE rule used : ", end="") + print(foreignKeyRules.get(dataRecord['UPDATE_RULE'])) + print(" DELETE rule used : ", end="") + print(foreignKeyRules.get(dataRecord['DELETE_RULE'])) + print(" Deferability : ", end="") + print(deferability.get(dataRecord['DEFERRABILITY'])) + + # Increment The loopCounter Variable And Print A Blank Line To Separate Foreign Key + # Records From Each Other + loopCounter += 1 + print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-free_result.py b/python_samples/Python_Examples/ibm_db/ibm_db-free_result.py new file mode 100644 index 0000000..873d793 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-free_result.py @@ -0,0 +1,202 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-free_result.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.free_result() API to # +# free system resources associated with a prepared SQL statement. # +# # +# Additional APIs used: # +# ibm_db.prepare() # +# ibm_db.execute() # +# ibm_db.num_rows() # +# ibm_db.set_option() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-free_result.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +preparedStmt = False +resultSet = False +returnCode = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT * FROM employee WHERE edlevel > 17" + +# Prepare The SQL Statement Just Defined +print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + preparedStmt = ibm_db.prepare(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit +if preparedStmt is False: + print("\nERROR: Unable to prepare the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Execute The SQL Statement Just Prepared +print("Executing the prepared SQL statement ... ", end="") +try: + resultSet = ibm_db.execute(preparedStmt) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Just Executed +# (This Information Should Not Be Available) +try: + numRows = ibm_db.num_rows(preparedStmt) +except Exception: + pass + +# Display An Appropriate Message, Based On The Information Returned +if numRows <= 0: + print("Unable to obtain information about the number of rows returned.\n") +else: + print("Number of rows returned by the query: " + str(numRows) + "\n") + +# Free System Resources That Are Associated With The Prepared Statement And Result Set Produced +print("Freeing system resources associated with the prepared statement ... ", end="") +try: + returnCode = ibm_db.free_result(preparedStmt) +except Exception: + pass + +# If The Appropriate System Resources Could Not Be Freed, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to free the appropriate system resources.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Create A Dictionary That Contains The Value Needed To Turn Row Prefetch Behavior On; +# This Enables Db2 To Determine The Number Of Rows That Are Returned By A Query (So The +# Entire Result Set Can Be Prefetched Into Memory, When Possible) +stmtOption = {ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON} + +# Attempt To Set The Statement Option Specified +print("Turning SQL_ATTR_ROWCOUNT_PREFETCH behavior ON ... ", end="") +try: + returnCode = ibm_db.set_option(preparedStmt, stmtOption, 0) +except Exception: + pass + +# If The Statement Option Could Not Be Set, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to set the statement option specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Execute The Prepared SQL Statement Again +print("Executing the prepared SQL statement again ... ", end="") +try: + resultSet = ibm_db.execute(preparedStmt) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Again +# (This Time, The Information Should Be Available) +try: + numRows = ibm_db.num_rows(preparedStmt) +except Exception: + pass + +# Display An Appropriate Message, Based On The New Information Returned +if numRows <= 0: + print("Unable to obtain information about the number of rows returned.\n") +else: + print("Number of rows returned by the query: " + str(numRows) + "\n") + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-get_option_CONNECTION.py b/python_samples/Python_Examples/ibm_db/ibm_db-get_option_CONNECTION.py new file mode 100644 index 0000000..4e90be8 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-get_option_CONNECTION.py @@ -0,0 +1,132 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-get_option_CONNECTION.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.get_option() API to # +# obtain the values that have been assigned to some of the connection options # +# available. # +# # +# Additional APIs used: # +# ibm_db.connect() # +# ibm_db.close() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-get_option_CONNECTION.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None + +# Create A Dictionary That Contains Connection Options That Can Be Set Before A Database +# Connection Is Established +connectOptions = {ibm_db.SQL_ATTR_AUTOCOMMIT : ibm_db.SQL_AUTOCOMMIT_ON, + ibm_db.SQL_ATTR_CURRENT_SCHEMA : 'db2inst1', + ibm_db.SQL_ATTR_INFO_PROGRAMNAME : 'ibm_db-get_option.py'} + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified (And Set The Appropriate +# Connection Options) +try: + dbConnection = ibm_db.connect(connString, '', '', connectOptions) +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if dbConnection is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Connection option settings:\n") +print("OPTION SETTING") +print("_________________________ ____________________") + +# Retrieve And Display The Ordinal Value For The Current AUTOCOMMIT Setting +value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_AUTOCOMMIT, 1) +print("SQL_ATTR_AUTOCOMMIT ", end="") +print(ord(value)) + +# Retrieve And Display The Schema Name That Was Set During The Connection +value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_CURRENT_SCHEMA, 1) +print("SQL_ATTR_CURRENT_SCHEMA " + value) + +# Retrieve And Display The Program Name That Was Set During The Connection +value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_PROGRAMNAME, 1) +print("SQL_ATTR_INFO_PROGRAMNAME " + value) + +# Add A Blank Line To The End Of The Report +print() + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not dbConnection is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = ibm_db.close(dbConnection) + except Exception: + pass + + # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-get_option_STATEMENT.py b/python_samples/Python_Examples/ibm_db/ibm_db-get_option_STATEMENT.py new file mode 100644 index 0000000..b34b32f --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-get_option_STATEMENT.py @@ -0,0 +1,136 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-get_option_STATEMENT.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.get_option() API to # +# assign a value to one of the statement options available. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-get_option_STATEMENT.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +cursorType = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Create A Dictionary That Contains Values For All Of The Statement Options That Can Be Set +stmtOptions = {ibm_db.SQL_ATTR_CURSOR_TYPE : ibm_db.SQL_CURSOR_STATIC, + ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON, + ibm_db.SQL_ATTR_QUERY_TIMEOUT : 10} + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT * FROM employee WHERE edlevel > 17" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement, stmtOptions) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified +print("Obtaining information about the type of cursor being used ... ", end="") +try: + cursorType = ibm_db.get_option(resultSet, ibm_db.SQL_ATTR_CURSOR_TYPE, 0) +except Exception: + pass + +# If Information About The Cursor Could Not Be Obtained, Display An Error Message And Exit +if cursorType is False: + print("\nERROR: Unable to obtain the information desired.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Verify That The Type Of Cursor Being Used Is Type Of Cursor That Was Specified +print("Type of cursor specified : Static (SQL_CURSOR_STATIC)") +print("Type of cursor being used: ", end="") + +if cursorType == ibm_db.SQL_CURSOR_FORWARD_ONLY: + print("Forward only (SQL_CURSOR_FORWARD_ONLY)\n") +elif cursorType == ibm_db.SQL_CURSOR_KEYSET_DRIVEN: + print("Keyset driven (SQL_CURSOR_KEYSET_DRIVEN)\n") +elif cursorType == ibm_db.SQL_CURSOR_DYNAMIC: + print("Dynamic (SQL_CURSOR_DYNAMIC)\n") +elif cursorType == ibm_db.SQL_CURSOR_STATIC: + print("Static (SQL_CURSOR_STATIC)\n") +else: + print("Unknown\n") + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-next_result.py b/python_samples/Python_Examples/ibm_db/ibm_db-next_result.py new file mode 100644 index 0000000..330950f --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-next_result.py @@ -0,0 +1,242 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-next_result.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.next_result() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# ibm_db.callproc() # +# ibm_db.fetch_tuple() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-next_result.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose of # +# assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +spName = "HIGH_EARNERS" +returnCode = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Used To Create A New Stored Procedure That +# Returns Three Result Sets +sqlStatement = "CREATE OR REPLACE PROCEDURE " + spName + " " +sqlStatement += "LANGUAGE SQL " +sqlStatement += "DYNAMIC RESULT SETS 3 " +sqlStatement += "READS SQL DATA " +sqlStatement += "NO EXTERNAL ACTION " +sqlStatement += "BEGIN " +sqlStatement += " DECLARE avgSalary INT DEFAULT 0; " +sqlStatement += " DECLARE c1 CURSOR WITH RETURN FOR " +sqlStatement += " SELECT firstnme, lastname, salary, job FROM employee " +sqlStatement += " WHERE job = 'DESIGNER' AND " +sqlStatement += " salary > avgSalary " +sqlStatement += " ORDER BY salary DESC; " +sqlStatement += " DECLARE c2 CURSOR WITH RETURN FOR " +sqlStatement += " SELECT firstnme, lastname, salary, job FROM employee " +sqlStatement += " WHERE job = 'ANALYST' AND " +sqlStatement += " salary > avgSalary " +sqlStatement += " ORDER BY salary DESC; " +sqlStatement += " DECLARE c3 CURSOR WITH RETURN FOR " +sqlStatement += " SELECT firstnme, lastname, salary, job FROM employee " +sqlStatement += " WHERE job = 'SALESREP' AND " +sqlStatement += " salary > avgSalary " +sqlStatement += " ORDER BY salary DESC; " +sqlStatement += " SELECT INT(AVG(salary)) INTO avgSalary FROM employee; " +sqlStatement += " OPEN c1; " +sqlStatement += " OPEN c2; " +sqlStatement += " OPEN c3; " +sqlStatement += "END" + +# Execute The SQL Statement Just Defined +print("Creating an SQL stored procedure named \"" + spName + "\" ... ", end="") +try: + returnCode = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Execute The Stored Procedure Just Created +resultSet_1 = None +print("Executing the " + spName + " procedure & retrieving the first ", end="") +print("result set produced ... ", end="") +try: + resultSet_1 = ibm_db.callproc(dbConnection, spName) +except Exception: + pass + +# If The Stored Procedure Specified Could Not Be Executed, Display An Error Message And Exit +if resultSet_1 is None: + print("\nERROR: Unable to execute the stored procedure specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message; Then Format And Display The Data Values Returned +else: + print("Done!\n") + +# Retrieve The Second Result Set From The Stored Procedure Just Executed +print("Retrieving the second result set produced by the " + spName, end="") +print(" procedure ... ", end="") +resultSet_2 = False +try: + resultSet_2 = ibm_db.next_result(resultSet_1) +except Exception: + pass + +# If The Second Result Set Could Not Be Retrieved, Display An Error Message And Exit +if resultSet_2 is False: + print("\nERROR: Unable to retrieve the second result set returned by the stored procedure.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Third Result Set From The Stored Procedure Just Executed +print("Retrieving the third result set produced by the " + spName, end="") +print(" procedure ... ", end="") +resultSet_3 = False +try: + resultSet_3 = ibm_db.next_result(resultSet_1) +except Exception: + pass + +# If The Third Result Set Could Not Be Retrieved, Display An Error Message And Exit +if resultSet_3 is False: + print("\nERROR: Unable to retrieve the third result set returned by the stored procedure.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Information retrieved:") + +# As Long As There Are Records To Retrieve, ... +noData = False +loopCounter = 1 +printHeader = True +dataRecord = True +while noData is False: + + # Display Record Header Information + if printHeader is True: + print("\n Result set " + str(loopCounter) + " details:\n") + print(" FIRSTNME LASTNAME SALARY JOB") + print(" ______________ __________________ __________ ________") + printHeader = False + + # Retrieve A Record From The Appropriate Result Set And Store It In A Python Tuple + if loopCounter is 1: + try: + dataRecord = ibm_db.fetch_tuple(resultSet_1) + except: + pass + elif loopCounter is 2: + try: + dataRecord = ibm_db.fetch_tuple(resultSet_2) + except: + pass + elif loopCounter is 3: + try: + dataRecord = ibm_db.fetch_tuple(resultSet_3) + except: + pass + + # If The Record Could Not Be Retrieved Or If There Was No Data To Retrieve, Increment The + # Loop Counter Variable And Set The Appropriate Variables To True + if dataRecord is False: + loopCounter += 1 + printHeader = True + dataRecord = True + + # If There Is No More Data To Retrieve, Set The "No Data" Flag And Exit The Loop + if loopCounter is 4: + noData = True + else: + continue + + # Otherwise, Extract And Display The Information Stored In The Data Record Retrieved + else: + print(" {:<14}" .format(dataRecord[0]), end="") + print(" {:<18}" .format(dataRecord[1]), end="") + print(" ${:>9}" .format(dataRecord[2]), end="") + print(" {:<10}" .format(dataRecord[3])) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-num_fields.py b/python_samples/Python_Examples/ibm_db/ibm_db-num_fields.py new file mode 100644 index 0000000..81f5f44 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-num_fields.py @@ -0,0 +1,119 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-num_fields.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db-num_fields() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-num_fields.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False +numColumns = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT * FROM project WHERE prstaff < 5" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Find Out How Many Columns Were Returned In The Result Set Produced By The Query Just Executed +print("Examining the result set produced ... ", end="") +try: + numColumns = ibm_db.num_fields(resultSet) +except Exception: + pass + +# If Information About The Number Columns Returned Could Not Be Obtained, Display An Error +# Message And Exit +if numColumns is False: + print("\nERROR: Unable to obtain information about the result set produced.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display The Information Retrieved +print("There are " + str(numColumns) + " columns in the result set produced by the query.\n") + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-num_rows.py b/python_samples/Python_Examples/ibm_db/ibm_db-num_rows.py new file mode 100644 index 0000000..31223ee --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-num_rows.py @@ -0,0 +1,173 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-num_rows.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db-num_rows() API. # +# # +# Additional APIs used: # +# ibm_db.autocommit() # +# ibm_db.prepare() # +# ibm_db.exec_many() # +# ibm_db.exec_rollback() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-num_rows.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +returnCode = False +preparedStmt = False +numRows = False +resultSet = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Turn Autocommit Behavior OFF +print("Turning AUTOCOMMIT behavior OFF ... ", end="") +returnCode = ibm_db.autocommit(dbConnection, 0) +if returnCode is False: + print("\nERROR: Unable to turn off AUTOCOMMIT behavior.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Define The INSERT Statement (With Parameter Markers) That Is To Be Used To Add Data +# To The DEPARTMENT Table +sqlStatement = "INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)" + +# Prepare The SQL Statement Just Defined +print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + preparedStmt = ibm_db.prepare(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit +if preparedStmt is False: + print("\nERROR: Unable to prepare the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Create A List Of Data Values That Are To Be Supplied For The Parameter Markers Coded +# In The INSERT Statement Specified +pmValues = (('K22', 'SALES', '000110'), + ('L22', 'FINANCE', '000120'), + ('M22', 'HUMAN RESOURCES', '000130')) + +# Execute The SQL Statement Just Prepared +print("Executing the prepared SQL statement ... ", end="") +try: + returnCode = ibm_db.execute_many(preparedStmt, pmValues) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message And Display The Number Of Records Added +else: + print("Done!\n") + +# Find Out How Many Rows Were Affected By The INSERT Operation +try: + numRows = ibm_db.num_rows(preparedStmt) +except Exception: + pass + +# If Information About The Number Rows Affected Could Not Be Obtained, Display An Error +# Message And Exit +if numRows is False: + print("\nERROR: Unable to obtain information about the number of rows affected.") + conn.closeConnection() + exit(-1) + +# Otherwise, Display The Information Obtained +else: + print("Number of rows affected by the INSERT operation: " + str(numRows) + "\n") + +# Back Out The Changes Just Made To The Database +print("Backing out changes made to the database ... ", end="") +try: + resultSet = ibm_db.rollback(dbConnection) +except Exception: + pass + +# If The Rollback Operation Could Not Be Performed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to roll back the previous operation.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-pconnect_DB.py b/python_samples/Python_Examples/ibm_db/ibm_db-pconnect_DB.py new file mode 100644 index 0000000..6df6390 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-pconnect_DB.py @@ -0,0 +1,175 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-pconnect_DB.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.pconnect() API to # +# create a pool of connections to a local Db2 database. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# ibm_db.num_rows() # +# ibm_db.close() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-pconnect_DB.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +dbConnection = list(range(10)) +resultSet = False +returnCode = False + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Display A Status Message Indicating An Attempt To Establish Ten Connections To A Db2 +# Database Is About To Be Made +print("\nEstablishing 10 connections to the \'" + dbName + "\' database ... \n") + +# Establish Ten Connections To The Local Db2 Database Specified +for loopCounter in range(10): + + # Attempt To Establish A Database Connection + try: + dbConnection[loopCounter] = ibm_db.pconnect(connString, '', '') + except Exception: + pass + + # If A Connection Could Not Be Established, Display An Error Message And Continue + if dbConnection[loopCounter] is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + continue + + # Otherwise, Display A "Connection Ready" Status Message + else: + print(" Connection {:>2} ready!" .format(loopCounter + 1)) + +# Add A Blank Line To The End Of The List Of Connections Created +print() + +# Retrieve Data From The Database Using Connection Number Five +if not dbConnection[5] is None: + + # Define The SQL Statement That Is To Be Executed + sqlStatement = "SELECT * FROM department" + + # Set The Statement Option That Is To be Used When the Statement Is Executed + stmtOption = {ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON} + + # Execute The SQL Statement Just Defined (Using The Desired Option) + print("Executing the SQL statement \"" + sqlStatement + "\" from Connection 5 ... ", end="") + currentConnection = dbConnection[5] + try: + resultSet = ibm_db.exec_immediate(currentConnection, sqlStatement, stmtOption) + except Exception: + pass + + # If The SQL Statement Could Not Be Executed, Display An Error Message And Continue + if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + + # Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Just + # Executed (There Should Be 14 Rows) + try: + numRows = ibm_db.num_rows(resultSet) + except Exception: + pass + + # Display An Appropriate Message, Based On The Information Returned + if numRows <= 0: + print("Unable to obtain information about the number of rows returned.\n") + else: + print("Number of rows returned by the query: " + str(numRows) + "\n") + + # Attempt To Close The Database Connection (Connection 5) + print("Closing database Connection 5 ... ", end="") + try: + returnCode = ibm_db.close(currentConnection) + except Exception: + pass + + # If The Connection Was Not Closed, Display An Error Message + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + + # Otherwise, Complete The Status Message + else: + print("Done!") + print("(Connection 5 has been returned the pool of connections opened earlier.)\n") + +# Display A Status Message Indicating An Attempt To Close The Remaining Db2 Database +# Connections Is About To Be Made +print("Closing all remaining connections to the \'" + dbName + "\' database ... \n") + +# Attempt To Close All Of The Db2 Database Connections That Were Opened Earlier +for loopCounter in range(10): + + # If The Specified Connection Is Open, Attempt To Close It + if not dbConnection[loopCounter] is None: + try: + returnCode = ibm_db.close(dbConnection[loopCounter]) + except Exception: + pass + + # If The Connection Could Not Be Closed, Display An Error Message And Continue + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + continue + + # Otherwise, Display A "Connection Closed" Status Message + else: + print(" Connection {:>2} closed!" .format(loopCounter + 1)) + +# Display A Status Message Indicating All Database Connections Have Been Returned To The +# Connection Pool +print("\nAll database connections have been returned the pool of connections opened earlier.\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-pconnect_SERVER.py b/python_samples/Python_Examples/ibm_db/ibm_db-pconnect_SERVER.py new file mode 100644 index 0000000..82c3a60 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-pconnect_SERVER.py @@ -0,0 +1,159 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-pconnect_SERVER.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.pconnect() API to # +# create a pool of connections to a remote Db2 server. # +# # +# Additional APIs used: # +# ibm_db.createdbNX() # +# ibm_db.close() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-pconnect_SERVER.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +hostName = "197.126.80.22" # IP Address Of Remote Server +portNum = "50000" # Port Number That Receives Db2 Connections On The Remote Server +userID = "db2inst2" # The Instance User ID At The Remote Server +passWord = "ibmdb2" # The Password For The Instance User ID At The Remote Server +svrConnection = list(range(10)) +dbName = "MY_DB" +returnCode = None + +# Construct The String That Will Be Used To Establish A Db2 Server Connection +connString = "DRIVER={IBM DB2 ODBC DRIVER}" +connString += ";ATTACH=TRUE" # Attach To A Server; Not A Database +connString += ";DATABASE=" # Ignored When Connecting To A Server +connString += ";HOSTNAME=" + hostName # Required To Connect To A Server +connString += ";PORT=" + portNum # Required To Connect To A Server +connString += ";PROTOCOL=TCPIP" # Required To Connect To A Server +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Display A Status Message Indicating An Attempt To Establish Ten Connections To A Remote +# Db2 Server Is About To Be Made +print("\nEstablishing 10 connections to the \'" + hostName + "\' server ... \n") + +# Establish Ten Connections To The Db2 Server Specified +for loopCounter in range(10): + + # Attempt To Establish A Db2 Server Connection + try: + svrConnection[loopCounter] = ibm_db.pconnect(connString, '', '') + except Exception: + pass + + # If A Connection Could Not Be Established, Display An Error Message And Continue + if svrConnection[loopCounter] is None: + print("\nERROR: Unable to connect to the \'" + hostName + "\' server.") + continue + + # Otherwise, Display A "Connection Ready" Status Message + else: + print(" Connection {:>2} ready!" .format(loopCounter + 1)) + +# Add A Blank Line To The End Of The List Of Connections Created +print() + +# Attempt To Create A New Database At The Remote Server Using Connection Number Five +if not svrConnection[5] is None: + print("Creating a database named " + dbName + " using Connection 5. Please wait.") + currentConnection = svrConnection[5] + try: + returnCode = ibm_db.createdbNX(currentConnection, dbName) + except Exception: + pass + + # If The Database Could Not Be Created, Display An Error Message And Exit + if returnCode is None: + print("ERROR: Unable to create the " + dbName + " database.\n") + errorMsg = ibm_db.conn_errormsg(svrConnection) + print(errorMsg + "\n") + + # Otherwise, Display A Status Message Indicating The Database Was Created + else: + print("\nThe database \"" + dbName + "\" has been created!\n") + + # Attempt To Close The Db2 Server Connection (Connection 5) + print("Closing Db2 server Connection 5 ... ", end="") + try: + returnCode = ibm_db.close(currentConnection) + except Exception: + pass + + # If The Connection Was Not Closed, Display An Error Message + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + hostName + " server.") + + # Otherwise, Complete The Status Message + else: + print("Done!") + print("(Connection 5 has been returned the pool of connections opened earlier.)\n") + +# Display A Status Message Indicating An Attempt To Close The Remaining Db2 Server +# Connections Is About To Be Made +print("Closing all remaining connections to the \'" + hostName + "\' server ... \n") + +# Attempt To Close All Of The Remaining Db2 Server Connections That Were Opened Earlier +for loopCounter in range(10): + + # If The Specified Connection Is Open, Attempt To Close It + if not svrConnection[loopCounter] is None: + try: + returnCode = ibm_db.close(svrConnection[loopCounter]) + except Exception: + pass + + # If The Connection Could Not Be Closed, Display An Error Message And Continue + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + hostName + " server.") + continue + + # Otherwise, Display A "Connection Closed" Status Message + else: + print(" Connection {:>2} closed!" .format(loopCounter + 1)) + +# Display A Status Message Indicating All Db2 Server Connections Have Been Returned To The +# Connection Pool +print("\nAll Db2 server connections have been returned the pool of connections opened earlier.\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-prepare.py b/python_samples/Python_Examples/ibm_db/ibm_db-prepare.py new file mode 100644 index 0000000..45a4ce7 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-prepare.py @@ -0,0 +1,136 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-prepare.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.prepare() API. # +# # +# Additional APIs used: # +# ibm_db.execute() # +# ibm_db.fetch_assoc() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-prepare.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +preparedStmt = False +returnCode = False +dataRecord = None + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT lastname, firstnme FROM employee WHERE job = 'PRES'" + +# Prepare The SQL Statement Just Defined +print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + preparedStmt = ibm_db.prepare(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit +if preparedStmt is False: + print("\nERROR: Unable to prepare the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Execute The SQL Statement Just Prepared +print("Executing the prepared SQL statement ... ", end="") +try: + returnCode = ibm_db.execute(preparedStmt) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Data Produced By The SQL Statement And Store It In A Python Dictionary +try: + dataRecord = ibm_db.fetch_assoc(preparedStmt) +except: + pass + +# If The Data Could Not Be Retrieved, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to retrieve the data produced by the SQL statement.") + conn.closeConnection() + exit(-1) + +# If The Data Could be Retrieved, Display It +else: + print("Query results:\n") + print("FIRSTNME LASTNAME") + print("__________ ________") + print("{:10} {:<24}\n" .format(dataRecord['FIRSTNME'], dataRecord['LASTNAME'])) + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-primary_keys.py b/python_samples/Python_Examples/ibm_db/ibm_db-primary_keys.py new file mode 100644 index 0000000..e6b9adf --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-primary_keys.py @@ -0,0 +1,134 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-primary_keys.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.primary_keys() API. # +# # +# Additional APIs used: # +# ibm_db.fetch_assoc() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-primary_keys.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +schemaName = userID.upper() +tableName = "PROJECT" +resultSet = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Retrieve Information About All Primary Keys That Have Been Defined For The +# Table Specified +print("Obtaining information about primary keys created for ", end="") +print("the " + schemaName + "." + tableName + " table ... ", end="") +try: + resultSet = ibm_db.primary_keys(dbConnection, None, schemaName, tableName) +except Exception: + pass + +# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to obtain the information desired\n.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# As Long As There Are Records (That Were Produced By The ibm_db.primary_keys API), ... +noData = False +loopCounter = 1 +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Information Retrieved + else: + + # Display Record Header Information + print("Primary key " + str(loopCounter) + " details:") + print("______________________________________") + + # Display The Information Stored In The Data Record Retrieved + print("Primary key table schema : {}" .format(dataRecord['TABLE_SCHEM'])) + print("Primary key table name : {}" .format(dataRecord['TABLE_NAME'])) + print("Primary key column name : {}" .format(dataRecord['COLUMN_NAME'])) + print("Primary key column number : {}" .format(dataRecord['KEY_SEQ'])) + print("Primary key name : {}" .format(dataRecord['PK_NAME'])) + + # Increment The loopCounter Variable And Print A Blank Line To Separate The + # Records From Each Other + loopCounter += 1 + print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-procedure_columns.py b/python_samples/Python_Examples/ibm_db/ibm_db-procedure_columns.py new file mode 100644 index 0000000..13a5a13 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-procedure_columns.py @@ -0,0 +1,185 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-procedure_columns.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.procedure_columns() # +# API. # +# # +# Additional APIs used: # +# ibm_db.fetch_assoc() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-procedure_columns.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +procedureName = 'VALIDATE_LENGTH' +resultSet = False +dataRecord = False +sqlDataTypes = {0 : "SQL_UNKNOWN_TYPE", 1 : "SQL_CHAR", 2 : "SQL_NUMERIC", 3 : "SQL_DECIMAL", + 4 : "SQL_INTEGER", 5 : "SQL_SMALLINT", 6 : "SQL_FLOAT", 7 : "SQL_REAL", 8 : "SQL_DOUBLE", + 9 : "SQL_DATETIME", 12 : "SQL_VARCHAR", 16 : "SQL_BOOLEAN", 19 : "SQL_ROW", + 91 : "SQL_TYPE_DATE", 92 : "SQL_TYPE_TIME", 93 : "SQL_TYPE_TIMESTAMP", + 95 : "SQL_TYPE_TIMESTAMP_WITH_TIMEZONE", -8 : "SQL_WCHAR", -9 : "SQL_WVARCHAR", + -10 : "SQL_WLONGVARCHAR", -95 : "SQL_GRAPHIC", -96 : "SQL_VARGRAPHIC", + -97 : "SQL_LONGVARGRAPHIC", -98 : "SQL_BLOB", -99 : "SQL_CLOB", -350 : "SQL_DBCLOB", + -360 : "SQL_DECFLOAT", -370 : "SQL_XML", -380 : "SQL_CURSORHANDLE", -400 : "SQL_DATALINK", + -450 : "SQL_USER_DEFINED_TYPE"} +sqlDateTimeSubtypes = {1 : "SQL_CODE_DATE", 2 : "SQL_CODE_TIME", 3 : "SQL_CODE_TIMESTAMP", + 4 : "SQL_CODE_TIMESTAMP_WITH_TIMEZONE"} + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Retrieve Information About The Parameters That Have Been Defined For A Particular +# Stored Procedure +print("Obtaining information about the parameters that have been defined for the ", end="") +print(procedureName + " procedure ... ", end="") +try: + resultSet = ibm_db.procedure_columns(dbConnection, None, '', procedureName, None) +except Exception: + pass + +# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to obtain the information desired\n.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# As Long As There Are Records (That Were Produced By The ibm_db.procedure_columns API), ... +noData = False +loopCounter = 1 +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Information Retrieved + else: + + # Display Record Header Information + print("Stored procedure parameter " + str(loopCounter) + " details:") + print("____________________________________________________________") + + # Display The Information Stored In The Data Record Retrieved + print("Procedure schema : {}" .format(dataRecord['PROCEDURE_SCHEM'])) + print("Procedure name : {}" .format(dataRecord['PROCEDURE_NAME'])) + print("Parameter name : {}" .format(dataRecord['COLUMN_NAME'])) + print("Parameter type : ", end="") + if dataRecord['COLUMN_TYPE'] == ibm_db.SQL_PARAM_INPUT: + print("Input (IN)") + elif dataRecord['COLUMN_TYPE'] == ibm_db.SQL_PARAM_INPUT_OUTPUT: + print("Input/output (INOUT)") + elif dataRecord['COLUMN_TYPE'] == ibm_db.SQL_PARAM_OUTPUT: + print("Output (OUT)") + else: + print("Unknown") + print("Data type : {}" .format(dataRecord['TYPE_NAME'])) + print("Size : {}" .format(dataRecord['COLUMN_SIZE'])) + print("Buffer size : {}" .format(dataRecord['BUFFER_LENGTH'])) + print("Scale (decimal digits) : ", end="") + if dataRecord['DECIMAL_DIGITS'] == None: + print("Not applicable") + else: + print("{}" .format(dataRecord['DECIMAL_DIGITS'])) + print("Precision radix : ", end="") + if dataRecord['NUM_PREC_RADIX'] == 10: + print("Exact numeric data type") + elif dataRecord['NUM_PREC_RADIX'] == 2: + print("Approximate numeric data type") + elif dataRecord['NUM_PREC_RADIX'] == None: + print("Not applicable") + print("Can accept NULL values : ", end="") + if dataRecord['NULLABLE'] == 1: + print("YES") + else: + print("NO") + print("Remarks : {}" .format(dataRecord['REMARKS'])) + print("Default value : {}" .format(dataRecord['COLUMN_DEF'])) + print("SQL data type : ", end="") + print(sqlDataTypes.get(dataRecord['SQL_DATA_TYPE'])) + print("SQL data/time subtype : ", end="") + print(sqlDateTimeSubtypes.get(dataRecord['SQL_DATETIME_SUB'])) + print("Length in octets : ", end="") + if dataRecord['CHAR_OCTET_LENGTH'] == None: + print("Not applicable") + else: + print("{}" .format(dataRecord['CHAR_OCTET_LENGTH'])) + print("Ordinal position : {}" .format(dataRecord['ORDINAL_POSITION'])) + print("Can accept or return \'None\' values : {}" .format(dataRecord['IS_NULLABLE'])) + + # Increment The loopCounter Variable And Print A Blank Line To Separate The + # Records From Each Other + loopCounter += 1 + print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-procedures.py b/python_samples/Python_Examples/ibm_db/ibm_db-procedures.py new file mode 100644 index 0000000..a28c277 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-procedures.py @@ -0,0 +1,134 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-procedures.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.procedures() API. # +# # +# Additional APIs used: # +# ibm_db.fetch_assoc() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-procedures.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +schemaName = userID.upper() +resultSet = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Retrieve Information About Stored Procedures That Have Been Defined In The +# Current User's Schema +print("Obtaining information about stored procedures in the ", end="") +print(schemaName + " schema ... ", end="") +try: + resultSet = ibm_db.procedures(dbConnection, None, schemaName, '') +except Exception: + pass + +# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to obtain the information desired\n.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# As Long As There Are Records (That Were Produced By The ibm_db.procedures API), ... +noData = False +loopCounter = 1 +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Information Retrieved + else: + + # Display Record Header Information + print("Stored procedure " + str(loopCounter) + " details:") + print("_______________________________________________") + + # Display The Information Stored In The Data Record Retrieved + print("Procedure schema : {}" .format(dataRecord['PROCEDURE_SCHEM'])) + print("Procedure name : {}" .format(dataRecord['PROCEDURE_NAME'])) + print("Number of input parameters : {}" .format(dataRecord['NUM_INPUT_PARAMS'])) + print("Number of output parameters : {}" .format(dataRecord['NUM_OUTPUT_PARAMS'])) + print("Number of result sets produced : {}" .format(dataRecord['NUM_RESULT_SETS'])) + print("Procedure comments : {}" .format(dataRecord['REMARKS'])) + + # Increment The loopCounter Variable And Print A Blank Line To Separate The + # Records From Each Other + loopCounter += 1 + print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-recreatedb_LOCAL.py b/python_samples/Python_Examples/ibm_db/ibm_db-recreatedb_LOCAL.py new file mode 100644 index 0000000..88de55a --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-recreatedb_LOCAL.py @@ -0,0 +1,104 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-recreatedb_LOCAL.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.recreatedb() API to # +# drop and recreate a local Db2 database. # +# # +# Additional APIs used: # +# ibm_db.conn_errormsg() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-recreatedb_LOCAL.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The query_sdb_dir() Function That Has Been Defined In The File Named "ibm_db_tools.py"; # +# This Function Contains The Programming Logic Needed To See If Information About A Specific # +# Database Can Be Found In The Db2 System Database Directory. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import query_sdb_dir + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +userID = "db2inst1" # User ID (Recognized By The Local Server) +passWord = "Passw0rd" # User Password +svrConnection = None +dbName = "MY_DB" +returnCode = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To The Local Db2 Server +conn = Db2ConnectionMgr('LOCAL_SVR', '', '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + svrConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Drop And Recreate A Database At The Local Server +print("Dropping and recreating a database named " + dbName + ". Please wait.") +try: + returnCode = ibm_db.recreatedb(svrConnection, dbName, 'UTF-8') +except Exception: + pass + +# If The Database Could Not Be Recreated, Display An Error Message And Exit +if returnCode is False: + print("ERROR: Unable to drop and recreate the " + dbName + " database.\n") + errorMsg = ibm_db.conn_errormsg(svrConnection) + print(errorMsg + "\n") + +# Otherwise, Display A Status Message And Verify That Information About The Database +# That Was Just Recreated Exists In The Db2 System Database Directory +else: + print("\nThe database \"" + dbName + "\" has been recreated!\n") + query_sdb_dir(dbName) + +# Close The Db2 Server Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-recreatedb_REMOTE.py b/python_samples/Python_Examples/ibm_db/ibm_db-recreatedb_REMOTE.py new file mode 100644 index 0000000..e67c673 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-recreatedb_REMOTE.py @@ -0,0 +1,108 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-recreatedb_REMOTE.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.recreatedb() API to # +# drop and recreate a database on a remote Db2 server. # +# # +# Additional APIs used: # +# ibm_db.conn_errormsg() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-recreatedb_REMOTE.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The query_sdb_dir() Function That Has Been Defined In The File Named "ibm_db_tools.py"; # +# This Function Contains The Programming Logic Needed To See If Information About A Specific # +# Database Can Be Found In The Db2 System Database Directory. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import query_sdb_dir + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +hostName = "197.126.80.22" # IP Address Of A Remote Server +portNum = "50000" # Port Number Used By Db2 +userID = "db2inst2" # User ID (Recognized By The Remote Server) +passWord = "ibmdb2" # User Password +svrConnection = None +dbName = "MY_DB" +returnCode = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Remote Db2 Server +conn = Db2ConnectionMgr('SERVER', '', hostName, portNum, userID, passWord) +conn.openConnection() +if conn.returnCode is True: + svrConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Delete (Drop) And Recreate A Database At The Remote Server +print("Dropping and recreating a database named " + dbName + " at the " + hostName + " server. Please wait.") +try: + returnCode = ibm_db.recreatedb(svrConnection, dbName, 'UTF-8') +except Exception: + pass + +# If The Database Could Not Be Recreated, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to drop and recreate the " + dbName + " database.\n") + errorMsg = ibm_db.conn_errormsg(svrConnection) + print(errorMsg + "\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Display A Status Message And Verify That Information About The Database +# That Was Just Recreated Exists In The Db2 System Database Directory +else: + print("\nThe database \"" + dbName + "\" has been recreated!\n") + query_sdb_dir(dbName) + +# Close The Db2 Server Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-result.py b/python_samples/Python_Examples/ibm_db/ibm_db-result.py new file mode 100644 index 0000000..67bcf22 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-result.py @@ -0,0 +1,112 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-result.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.fetch_row() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# ibm_db.fetch_row() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-result.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +resultSet = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT deptname FROM department WHERE admrdept = 'A00'" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("DEPTNAME") +print("____________________________") + +# As Long As There Are Records In The Result Set Produced, ... +while (ibm_db.fetch_row(resultSet) is True): + + # Display The Data Retrieved + print(ibm_db.result(resultSet, 0)) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-rollback.py b/python_samples/Python_Examples/ibm_db/ibm_db-rollback.py new file mode 100644 index 0000000..7c61784 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-rollback.py @@ -0,0 +1,162 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-rollback.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.rollback() API. # +# # +# Additional APIs used: # +# ibm_db.autocommit() # +# ibm_db.exec_immediate() # +# ibm_db.stmt_errormsg() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-rollback.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The get_row_count() Function That Has Been Defined In The File Named "ibm_db_tools.py"; # +# This Function Contains The Programming Logic Needed To Obtain And Display The Number Of Rows # +# (Records) Found In A Db2 Database Table. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import get_row_count + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +returnCode = False +resultSet = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Turn Autocommit Behavior OFF +print("Turning AUTOCOMMIT behavior OFF ... ", end="") +try: + returnCode = ibm_db.autocommit(dbConnection, ibm_db.SQL_AUTOCOMMIT_OFF) +except Exception: + pass + +# If AUTOCOMMIT Behavior Could Not Be Turned OFF, Display An Error Message And Continue +if returnCode is False: + print("\nERROR: Unable to turn AUTOCOMMIT behavior OFF.") + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table +returnCode = get_row_count(dbConnection, 'DEPARTMENT') +if returnCode is False: + conn.closeConnection() + exit(-1) + +# Define The INSERT Statement That Is To Be Used To Add Data To The DEPARTMENT Table +sqlStatement = "INSERT INTO department VALUES('K01', 'SALES', '000130', 'K01', NULL)" + +# Execute The SQL Statement Just Defined +print("Inserting a record into the DEPARTMENT table ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the INSERT statement specified.") + errorMsg = ibm_db.stmt_errormsg() + print("\n" + errorMsg + "\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display The Number Of Rows That Exist In The DEPARTMENT Table Now +# (The Number Returned Should Change) +returnCode = get_row_count(dbConnection, 'DEPARTMENT') +if returnCode is False: + conn.closeConnection() + exit(-1) + +# Back Out The Changes Just Made To The Database +print("Backing out changes made to the database ... ", end="") +resultSet = False +try: + resultSet = ibm_db.rollback(dbConnection) +except Exception: + pass + +# If The Rollback Operation Could Not Be Performed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to roll back the previous operation.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display The Number Of Rows That Exist In The DEPARTMENT Table Now +# (The Number Should Revert Back To The Original Value) +returnCode = get_row_count(dbConnection, 'DEPARTMENT') +if returnCode is False: + conn.closeConnection() + exit(-1) + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-server_info.py b/python_samples/Python_Examples/ibm_db/ibm_db-server_info.py new file mode 100644 index 0000000..7a41c9b --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-server_info.py @@ -0,0 +1,194 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-server_info.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.server_info() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-server_info.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +svrConnection = None +serverInfo = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Server +conn = Db2ConnectionMgr('SERVER', '', '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + svrConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Obtain Information About The Db2 Server Being Used +print("Obtaining information about the server ... ", end="") +try: + serverInfo = ibm_db.server_info(svrConnection) +except Exception: + pass + +# If Information About The Server Could Not Be Obtained, Display An Error Message +if serverInfo is False: + print("\nERROR: Unable to obtain server information.\n") + +# Otherwise, Complete The Status Message; Then Format And Display The Data Retrieved +else: + print("Done!\n") + + # Display A Report Header + print("Server details:") + print("_____________________________________________________________________________") + + # Display The Server Data + print("Db2 database server name : {}" .format(serverInfo.DBMS_NAME)) + print("Db2 software version : {}" .format(serverInfo.DBMS_VER)) + print("Db2 instance name : {}" .format(serverInfo.INST_NAME)) + print("Database codepage used : {}" .format(serverInfo.DB_CODEPAGE)) + print("Database name : {}" .format(serverInfo.DB_NAME)) + + print("Isolation levels supported : ", end="") + for loopCounter in range(0, len(serverInfo.ISOLATION_OPTION)): + if serverInfo.ISOLATION_OPTION[loopCounter] == 'UR': + print("Uncommitted Read (UR)", end="") + elif serverInfo.ISOLATION_OPTION[loopCounter] == 'CS': + print("Cursor Stability (CS)", end="") + elif serverInfo.ISOLATION_OPTION[loopCounter] == 'RS': + print("Read Stability (RS)", end="") + elif serverInfo.ISOLATION_OPTION[loopCounter] == 'RR': + print("Repeatable Read (RR)", end="") + elif serverInfo.ISOLATION_OPTION[loopCounter] == 'NC': + print("No Commit", end="") + if loopCounter < len(serverInfo.ISOLATION_OPTION) - 1: + print("\n" + " " * 43, end="") + print() + + print("Default isolation level used : ", end="") + if serverInfo.DFT_ISOLATION == 'NC': + print("No Commit") + else: + print("{}" .format(serverInfo.DFT_ISOLATION)) + + print("Identifier delimiter character : ", end="") + print("{}" .format(serverInfo.IDENTIFIER_QUOTE_CHAR)) + + print("Use of % and _ as wildcards supported : ", end="") + if serverInfo.LIKE_ESCAPE_CLAUSE == True: + print("Yes") + else: + print("No") + + print("Maximum column name length : ", end="") + print("{:<7} bytes" .format(serverInfo.MAX_COL_NAME_LEN)) + print("Maximum SQL identifier length : ", end="") + print("{:<7} characters" .format(serverInfo.MAX_IDENTIFIER_LEN)) + print("Maximum index size (combined columns) : ", end="") + print("{:<7} bytes" .format(serverInfo.MAX_INDEX_SIZE)) + print("Maximum procedure name length : ", end="") + print("{:<7} bytes" .format(serverInfo.MAX_PROC_NAME_LEN)) + print("Maximum row size : ", end="") + print("{:<7} bytes" .format(serverInfo.MAX_ROW_SIZE)) + print("Maximum schema name length : ", end="") + print("{:<7} bytes" .format(serverInfo.MAX_SCHEMA_NAME_LEN)) + print("Maximum SQL statement length : ", end="") + print("{:<7} bytes" .format(serverInfo.MAX_STATEMENT_LEN)) + print("Maximum table name length : ", end="") + print("{:<7} bytes" .format(serverInfo.MAX_TABLE_NAME_LEN)) + + print("NOT NULL columns supported : ", end="") + if serverInfo.NON_NULLABLE_COLUMNS == True: + print("Yes") + else: + print("No") + print("CALL statement supported : ", end="") + if serverInfo.PROCEDURES == True: + print("Yes") + else: + print("No") + + print("Characters supported in identifier names : A-Z, 0-9, _, ", end="") + tempString = (", ".join(serverInfo.SPECIAL_CHARS)) + endingPos = tempString.find(tempString[-1]) + tempString = tempString[:int(endingPos)] + tempString += "and " + serverInfo.SPECIAL_CHARS[-1] + print(tempString) + + print("ANSI/ISO SQL-92 conformance level : ", end="") + if serverInfo.SQL_CONFORMANCE == 'ENTRY': + print("Entry-level compliance\n") + elif serverInfo.SQL_CONFORMANCE == 'INTERMEDIATE': + print("Intermediate-level compliance\n") + elif serverInfo.SQL_CONFORMANCE == 'FULL': + print("Full compliance\n") + elif serverInfo.SQL_CONFORMANCE == 'FIPS127': + print("FIPS-127-2 transitional compliance\n") + + # Display Another Header, Followed By A Five-Column List Of Reserved Keywords + print("Reserved keywords:") + print('_' * 92 + "\n") + loopCounter = 0 + while loopCounter < len(serverInfo.KEYWORDS): + colNumber = 0 + while colNumber < 5: + print("{:<19}".format(serverInfo.KEYWORDS[loopCounter]), end="") + colNumber += 1 + loopCounter += 1 + if colNumber is 5: + print() + if loopCounter is len(serverInfo.KEYWORDS): + break + +# End The Last Row And Add A Blank Line To The End Of The Report +print("\n") + +# Close The Server Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-set_option_CONNECTION.py b/python_samples/Python_Examples/ibm_db/ibm_db-set_option_CONNECTION.py new file mode 100644 index 0000000..0407dc7 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-set_option_CONNECTION.py @@ -0,0 +1,155 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-set_option_CONNECTION.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.set_option() API to # +# assign values to some of the connection options available. # +# # +# Additional APIs used: # +# ibm_db.connect() # +# ibm_db.get_option() # +# ibm_db.close() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-set_option_CONNECTION.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + dbConnection = ibm_db.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if dbConnection is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Create A Dictionary That Contains Values For The Connection Options That Can Only Be Set +# After A Database Connection Is Established +connectOptions = {ibm_db.SQL_ATTR_INFO_ACCTSTR : 'RESANDERS@IBM', + ibm_db.SQL_ATTR_INFO_APPLNAME : 'ibm_db-set_option.py', + ibm_db.SQL_ATTR_INFO_USERID : 'db2inst1', + ibm_db.SQL_ATTR_INFO_WRKSTNNAME : 'ibm_UDOO_X86'} + +# Attempt To Set The Connection Options Specified +print("Assigning values to four different connection options ... ", end="") +try: + returnCode = ibm_db.set_option(dbConnection, connectOptions, 1) +except Exception: + pass + +# If The Connection Options Could Not Be Set, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to set the connection options specified.\n") + if not dbConnection is None: + ibm_db.close(dbConnection) + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Connection option settings:\n") +print("OPTION SETTING") +print("________________________ ____________________") + +# Retrieve And Display The Accounting String That Was Defined For The Client +value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_ACCTSTR, 1) +print("SQL_ATTR_INFO_ACCTSTR " + value) + + +# Retrieve And Display The Application Name That Was Defined For The Client +value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_APPLNAME, 1) +print("SQL_ATTR_INFO_APPLNAME " + value) + +# Retrieve And Display The User ID That Was Defined For The Client +value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_USERID, 1) +print("SQL_ATTR_INFO_USERID " + value) + +# Retrieve And Display The Workstation Name That Was Defined For The Client +value = ibm_db.get_option(dbConnection, ibm_db.SQL_ATTR_INFO_WRKSTNNAME, 1) +print("SQL_ATTR_INFO_WRKSTNNAME " + value) + +# Add A Blank Line To The End Of The Report +print() + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not dbConnection is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = ibm_db.close(dbConnection) + except Exception: + pass + + # If The Db2 Server Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-set_option_STATEMENT.py b/python_samples/Python_Examples/ibm_db/ibm_db-set_option_STATEMENT.py new file mode 100644 index 0000000..62a3470 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-set_option_STATEMENT.py @@ -0,0 +1,214 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-set_option_STATEMENT.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.set_option() API to # +# assign a value to one of the statement options available. # +# # +# Additional APIs used: # +# ibm_db.prepare() # +# ibm_db.execute() # +# ibm_db.num_rows() # +# ibm_db.free_result() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-get_option_STATEMENT.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +preparedStmt = False +resultSet = False +returnCode = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Define The SQL Statement That Is To Be Executed +sqlStatement = "SELECT * FROM employee WHERE edlevel > 17" + +# Prepare The SQL Statement Just Defined +print("Preparing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + preparedStmt = ibm_db.prepare(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Prepared By Db2, Display An Error Message And Exit +if preparedStmt is False: + print("\nERROR: Unable to prepare the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Execute The SQL Statement Just Prepared +print("Executing the prepared SQL statement ... ", end="") +try: + resultSet = ibm_db.execute(preparedStmt) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Just Executed +# (This Information Should Not Be Available) +try: + numRows = ibm_db.num_rows(preparedStmt) +except Exception: + pass + +# Display An Appropriate Message, Based On The Information Returned +if numRows <= 0: + print("Unable to obtain information about the number of rows returned.\n") +else: + print("Number of rows returned by the query: " + str(numRows) + "\n") + +# Free System Resources That Are Associated With The Prepared Statement And Result Set Produced +print("Freeing system resources associated with the prepared statement ... ", end="") +try: + returnCode = ibm_db.free_result(preparedStmt) +except Exception: + pass + +# If The Appropriate System Resources Could Not Be Freed, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to free the appropriate system resources.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Create A Dictionary That Contains The Value Needed To Turn Row Prefetch Behavior On; +# This Enables Db2 To Determine The Number Of Rows That Are Returned By A Query (So The +# Entire Result Set Can Be Prefetched Into Memory, When Possible) +stmtOption = {ibm_db.SQL_ATTR_ROWCOUNT_PREFETCH : ibm_db.SQL_ROWCOUNT_PREFETCH_ON} + +# Attempt To Set The Statement Option Specified +print("Turning SQL_ATTR_ROWCOUNT_PREFETCH behavior ON ... ", end="") +try: + returnCode = ibm_db.set_option(preparedStmt, stmtOption, 0) +except Exception: + pass + +# If The Statement Option Could Not Be Set, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to set the statement option specified.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Execute The Prepared SQL Statement Again +print("Executing the prepared SQL statement again ... ", end="") +try: + resultSet = ibm_db.execute(preparedStmt) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Try To Find Out How Many Rows Are In Result Set That Was Produced By The Query Again +# (This Time, The Information Should Be Available) +try: + numRows = ibm_db.num_rows(preparedStmt) +except Exception: + pass + +# Display An Appropriate Message, Based On The New Information Returned +if numRows <= 0: + print("Unable to obtain information about the number of rows returned.\n") +else: + print("Number of rows returned by the query: " + str(numRows) + "\n") + +# Free The Appropriate System Resources Again +try: + returnCode = ibm_db.free_result(preparedStmt) +except Exception: + pass + +# If The Appropriate System Resources Could Not Be Freed, Display An Error Message And Exit +if returnCode is False: + print("\nERROR: Unable to free the appropriate system resources.\n") + conn.closeConnection() + exit(-1) + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-special_columns.py b/python_samples/Python_Examples/ibm_db/ibm_db-special_columns.py new file mode 100644 index 0000000..f727686 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-special_columns.py @@ -0,0 +1,157 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-special_columns.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.special_columns() API. # +# # +# Additional APIs used: # +# ibm_db.fetch_assoc() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-special_columns.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +schemaName = userID.upper() +tableName = "EMPLOYEE" +resultSet = False +dataRecord = False +sqlDataTypes = {0 : "SQL_UNKNOWN_TYPE", 1 : "SQL_CHAR", 2 : "SQL_NUMERIC", 3 : "SQL_DECIMAL", + 4 : "SQL_INTEGER", 5 : "SQL_SMALLINT", 6 : "SQL_FLOAT", 7 : "SQL_REAL", 8 : "SQL_DOUBLE", + 9 : "SQL_DATETIME", 12 : "SQL_VARCHAR", 16 : "SQL_BOOLEAN", 19 : "SQL_ROW", + 91 : "SQL_TYPE_DATE", 92 : "SQL_TYPE_TIME", 93 : "SQL_TYPE_TIMESTAMP", + 95 : "SQL_TYPE_TIMESTAMP_WITH_TIMEZONE", -8 : "SQL_WCHAR", -9 : "SQL_WVARCHAR", + -10 : "SQL_WLONGVARCHAR", -95 : "SQL_GRAPHIC", -96 : "SQL_VARGRAPHIC", + -97 : "SQL_LONGVARGRAPHIC", -98 : "SQL_BLOB", -99 : "SQL_CLOB", -350 : "SQL_DBCLOB", + -360 : "SQL_DECFLOAT", -370 : "SQL_XML", -380 : "SQL_CURSORHANDLE", -400 : "SQL_DATALINK", + -450 : "SQL_USER_DEFINED_TYPE"} + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Retrieve Information About Unique Row Identifier Columns That Have Been +# Defined For The Table Specified +print("Obtaining information about unique row identifier columns that have been") +print("defined for the " + schemaName + "." + tableName + " table ... ", end="") +try: + resultSet = ibm_db.special_columns(dbConnection, None, schemaName, tableName, 0) + +except Exception: + pass + +# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to obtain the information desired\n.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# As Long As There Are Records (That Were Produced By The ibm_db.special_columns API), ... +noData = False +loopCounter = 1 +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Information Retrieved + else: + + # Display Record Header Information + print("Primary key/unique index " + str(loopCounter) + " details:") + print("___________________________________") + + # Display The Information Stored In The Data Record Retrieved + print("Column name : {}" .format(dataRecord['COLUMN_NAME'])) + print("Data type : {}" .format(dataRecord['TYPE_NAME'])) + print("SQL data type : ", end="") + print(sqlDataTypes.get(dataRecord['DATA_TYPE'])) + print("Column size : {}" .format(dataRecord['COLUMN_SIZE'])) + print("Buffer size : {}" .format(dataRecord['BUFFER_LENGTH'])) + print("Scale (decimal digits) : {}" .format(dataRecord['DECIMAL_DIGITS'])) + + print("Scope : ", end="") + if dataRecord['SCOPE'] == 0: + print("Row ID is valid only while the\n" + " " * 25, end="") + print("cursor is positioned on the row") + elif dataRecord['SCOPE'] == 1: + print("Row ID is valid for the\n" + " " * 25, end="") + print("duration of the transaction") + elif dataRecord['SCOPE'] == 2: + print("Row ID is valid for the\n" + " " * 25, end="") + print("duration of the connection") + + # Increment The loopCounter Variable And Print A Blank Line To Separate The + # Records From Each Other + loopCounter += 1 + print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-statistics.py b/python_samples/Python_Examples/ibm_db/ibm_db-statistics.py new file mode 100644 index 0000000..fe03f22 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-statistics.py @@ -0,0 +1,160 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-statistics.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.statistics() API. # +# # +# Additional APIs used: # +# ibm_db.fetch_assoc() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-statistics.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +schemaName = userID.upper() +tableName = "EMPLOYEE" +resultSet = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Retrieve Information About The Indexes And Statistics That Exist For A +# Specified Table +print("Obtaining statistics for the " + schemaName + ".", end="") +print(tableName + " table ... ", end="") +try: + resultSet = ibm_db.statistics(dbConnection, None, schemaName, tableName, True) +except Exception: + pass + +# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to obtain the information desired\n.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# As Long As There Are Records (That Were Produced By The ibm_db.statistics API), ... +noData = False +loopCounter = 1 +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Information Retrieved + else: + + # Display Record Header Information + print("Record number " + str(loopCounter) + " details:") + print("______________________________________________") + + # Display The Information Stored In The Data Record Retrieved + print("Type of data : ", end="") + if dataRecord['TYPE'] == ibm_db.SQL_TABLE_STAT: + print("Table") + elif dataRecord['TYPE'] == ibm_db.SQL_INDEX_CLUSTERED: + print("Clustered index") + elif dataRecord['TYPE'] == ibm_db.SQL_INDEX_OTHER: + print("Index") + print("Table schema : {}" .format(dataRecord['TABLE_SCHEM'])) + print("Table name : {}" .format(dataRecord['TABLE_NAME'])) + print("Index qualifier : {}" .format(dataRecord['INDEX_QUALIFIER'])) + print("Index name : {}" .format(dataRecord['INDEX_NAME'])) + print("Column name : {}" .format(dataRecord['COLUMN_NAME'])) + print("Column position in index : {}" .format(dataRecord['ORDINAL_POSITION'])) + if not dataRecord['INDEX_NAME'] is None: + print("Index used to enforce uniqueness : ", end="") + if dataRecord['NON_UNIQUE'] == ibm_db.SQL_FALSE: + print("No") + elif dataRecord['NON_UNIQUE'] == ibm_db.SQL_TRUE: + print("Yes") + if not dataRecord['INDEX_NAME'] is None: + print("Data order : ", end="") + if dataRecord['ASC_OR_DESC'] == 'A': + print("Ascending") + elif dataRecord['ASC_OR_DESC'] == 'D': + print("Descending") + if not dataRecord['INDEX_NAME'] is None: + print("Number of unique values : {}" .format(dataRecord['CARDINALITY'])) + else: + print("Number of rows (records) : {}" .format(dataRecord['CARDINALITY'])) + + print("Number of pages used : {}" .format(dataRecord['PAGES'])) + + # Increment The loopCounter Variable And Print A Blank Line To Separate The + # Records From Each Other + loopCounter += 1 + print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-stmt_error.py b/python_samples/Python_Examples/ibm_db/ibm_db-stmt_error.py new file mode 100644 index 0000000..ba69d2a --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-stmt_error.py @@ -0,0 +1,97 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-stmt_error.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.stmt_error() API. # +# # +# Additional APIs used: # +# ibm_db.exec_immediate() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-stmt_error.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +sqlStatement = " " # An Empty SQL Statement Is Used To Force An Error To Occur +resultSet = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Execute The SQL Statement Specified +print("Executing the SQL statement specified ... ", end="") +try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement.") + errorCode = ibm_db.stmt_error() + print("\nSQLSTATE: "+ errorCode + "\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-stmt_errormsg.py b/python_samples/Python_Examples/ibm_db/ibm_db-stmt_errormsg.py new file mode 100644 index 0000000..b51b47f --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-stmt_errormsg.py @@ -0,0 +1,98 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-stmt_errormsg.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.stmt_errormsg() API. # +# # +# Additional APIs used: # +# ibm_db.prepare() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-stmt_errormsg.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +sqlStatement = " " # An Empty SQL Statement Is Used To Force An Error To Occur +preparedStmt = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Prepare The SQL Statement Specified +print("Preparing the SQL statement specified for execution ... ", end="") +try: + preparedStmt = ibm_db.prepare(dbConnection, sqlStatement) +except Exception: + pass + +# If Db2 Could Not Parse And Prepare The SQL Statement Correctly, Display An Error Message +# And Exit +if preparedStmt is False: + print("\nERROR: Unable to prepare the SQL statement specified.") + errorMsg = ibm_db.stmt_errormsg() + print("\n" + errorMsg + "\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-table_privileges.py b/python_samples/Python_Examples/ibm_db/ibm_db-table_privileges.py new file mode 100644 index 0000000..ebda270 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-table_privileges.py @@ -0,0 +1,135 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-table_privileges.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.table_privileges() API. # +# # +# Additional APIs used: # +# ibm_db.fetch_assoc() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-table_privileges.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +schemaName = userID.upper() +tableName = "PROJECT" +resultSet = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Retrieve Information About All Of The Privileges That Have Been Defined For The +# Table Specified +print("Obtaining information about privileges that exist for the ", end="") +print(schemaName + "." + tableName + " table ... ", end="") +try: + resultSet = ibm_db.table_privileges(dbConnection, None, schemaName, tableName) +except Exception: + pass + +# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to obtain the information desired.\n") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# As Long As There Are Records (That Were Produced By The ibm_db.table_privileges API), ... +noData = False +loopCounter = 1 +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Information Retrieved + else: + + # Display Record Header Information + print("Table privilege " + str(loopCounter) + " details:") + print("___________________________________") + + # Display The Information Stored In The Data Record Retrieved + print("Schema name : {}" .format(dataRecord['TABLE_SCHEM'])) + print("Table name : {}" .format(dataRecord['TABLE_NAME'])) + print("Privilege grantor : {}" .format(dataRecord['GRANTOR'])) + print("Privilege recipient : {}" .format(dataRecord['GRANTEE'])) + print("Privilege : {}" .format(dataRecord['PRIVILEGE'])) + print("Privilege is grantable : {}" .format(dataRecord['IS_GRANTABLE'])) + + # Increment The loopCounter Variable And Print A Blank Line To Separate The + # Records From Each Other + loopCounter += 1 + print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db-tables.py b/python_samples/Python_Examples/ibm_db/ibm_db-tables.py new file mode 100644 index 0000000..d602dca --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db-tables.py @@ -0,0 +1,132 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db-tables.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db.tables() API. # +# # +# Additional APIs used: # +# ibm_db.fetch_assoc() # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db-tables.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The Db2ConnectionMgr Class Definition, Attributes, And Methods That Have Been Defined # +# In The File Named "ibm_db_tools.py"; This Class Contains The Programming Logic Needed To # +# Establish And Terminate A Connection To A Db2 Server Or Database # +#-------------------------------------------------------------------------------------------------# +from ibm_db_tools import Db2ConnectionMgr + +#-------------------------------------------------------------------------------------------------# +# Import The ipynb_exit Class Definition, Attributes, And Methods That Have Been Defined In The # +# File Named "ipynb_exit.py"; This Class Contains The Programming Logic Needed To Allow "exit()" # +# Functionality To Work Without Raising An Error Or Stopping The Kernel If The Application Is # +# Invoked In A Jupyter Notebook # +#-------------------------------------------------------------------------------------------------# +from ipynb_exit import exit + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" +userID = "db2inst1" +passWord = "Passw0rd" +dbConnection = None +schemaName = userID.upper() +resultSet = False +dataRecord = False + +# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database +conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord) +conn.openConnection() +if conn.returnCode is True: + dbConnection = conn.connectionID +else: + conn.closeConnection() + exit(-1) + +# Attempt To Retrieve Information About The Tables In The Current User's Schema Whose Name +# Begins With The Letter "P" +print("Obtaining information about select tables in the ", end="") +print(schemaName + " schema ... ", end="") +try: + resultSet = ibm_db.tables(dbConnection, None, schemaName, 'P%', 'TABLE') +except Exception: + pass + +# If The Information Desired Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to obtain the information desired\n.") + conn.closeConnection() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# As Long As There Are Records (That Were Produced By The ibm_db.tables API), ... +noData = False +loopCounter = 1 +while noData is False: + + # Retrieve A Record And Store It In A Python Dictionary + try: + dataRecord = ibm_db.fetch_assoc(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved Or If There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if dataRecord is False: + noData = True + + # Otherwise, Display The Information Retrieved + else: + + # Display Record Header Information + print("Table " + str(loopCounter) + " details:") + print("________________________") + + # Display The Information Stored In The Data Record Retrieved + print("Table schema : {}" .format(dataRecord['TABLE_SCHEM'])) + print("Table name : {}" .format(dataRecord['TABLE_NAME'])) + print("Table type : {}" .format(dataRecord['TABLE_TYPE'])) + print("Description : {}" .format(dataRecord['REMARKS'])) + + # Increment The loopCounter Variable And Print A Blank Line To Separate The + # Records From Each Other + loopCounter += 1 + print() + +# Close The Database Connection That Was Opened Earlier +conn.closeConnection() + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db/ibm_db_tools.py b/python_samples/Python_Examples/ibm_db/ibm_db_tools.py new file mode 100644 index 0000000..67b59b9 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ibm_db_tools.py @@ -0,0 +1,360 @@ +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_tools.py # +# # +# PURPOSE: This file contains classes and functions that are used by many of the ibm_db sample # +# programs and Jupyter Notebooks. # +# # +# APIs used: # +# ibm_db.connect() # +# ibm_db.conn_errormsg() # +# ibm_db.close() # +# ibm_db.exec_immediate() # +# ibm_db.fetch_tuple() # +# # +# USAGE: Add the following lines of code at the beginning of an ibm_db sample program: # +# # +# from ibm_db_tools import Db2ConnectionMgr # +# from ibm_db_tools import get_row_count # +# from ibm_db_tools import query_sdb_dir (Use with Python sample programs only) # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose of # +# assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import subprocess # Required To Execute A Shell Command +import socket # Provides Access To The BSD Low-Level Networking Interface +import string # Privides APIs Needed To Work With Strings +from io import StringIO # Implements A File-Like Class That Reads And Writes A String + # Buffer (i.e., A Memory File) +from IPython import get_ipython # Simple Function To Call To Get The Current Interactive Shell + # Instance +import ibm_db # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# CLASS NAME: Db2ConnectionMgr() # +# PURPOSE: This class contains attributes and methods that can be used to establish and # +# terminate a connection to a Db2 server or database. # +#-------------------------------------------------------------------------------------------------# +class Db2ConnectionMgr(): + """A simple class that manages a Db2 server or database connection.""" + + #---------------------------------------------------------------------------------------------# + # FUNCTION NAME: __init()__ # + # PURPOSE: This method initializes all attributes used by an instance of the # + # Db2ConnectionMgr class. # + # PARAMETERS: dbName - Db2 server or database name # + # dsType - Db2 server or database type ('DB' or 'SERVER') # + # hostName - Db2 server host name or IP address # + # portNum - Port number Db2 uses at the specified server # + # userID - User authentication ID # + # passWord - User password # + #---------------------------------------------------------------------------------------------# + def __init__(self, dsType='', dbName=None, hostName='', portNum='', + userID=None, passWord=None): + """Initialize Db2 server or database name, user ID, and password attributes.""" + + self.dsType = dsType + self.dbName = dbName + self.hostName = hostName + self.portNum = portNum + self.userID = userID + self.passWord = passWord + self.connectionID = None + self.returnCode = False + + # If A Data Source Type Was Not Specified, Use 'DB' By Default + if self.dsType is '': + self.dsType = 'DB' + + #---------------------------------------------------------------------------------------------# + # FUNCTION NAME: openConnection() # + # PURPOSE: This method attempts to open the Db2 server or database connection # + # specified. # + # PARAMETERS: None # + #---------------------------------------------------------------------------------------------# + def openConnection(self): + """Attempt to establish a Db2 server or database connection.""" + + # Define And Initialize The Appropriate Local Variables + connString = "DRIVER={IBM DB2 ODBC DRIVER}" + msgString = "" + + # If A Host Name Was Not Specified, Use The Name That Is Assigned To The Current Server + if self.hostName is '': + self.hostName = socket.gethostname() + + # If A Port Number Was Not Specified, Use Port Number 50000 + if self.portNum is '': + self.portNum = '50000' + + # Display An Appropriate Status Message And Add The Correct "ATTACH" Value To The + # Connection String Variable (connString) + msgString = "\nConnecting to the " + if self.dsType is 'LOCAL_SVR': + print(msgString + "local server ... ", end="") + if get_ipython(): # If Running With IPython, ... + connString += ";ATTACH=TRUE" # Attach To A Server; Not A Database + else: + connString = "ATTACH=TRUE" # Attach To A Server; Not A Database + elif self.dsType is 'SERVER': + print(msgString + self.hostName + " server ... ", end="") + connString += ";ATTACH=TRUE" # Attach To A Server; Not A Database + else: + print(msgString + self.dbName + " database ... ", end="") + connString += ";ATTACH=FALSE" # Attach To A Database; Not A Server + + # If Appropriate, Construct The Portion Of The Connection String That Will Be Used To + # Establish A Connection To The Local Db2 Server + if self.dsType is 'LOCAL_SVR': + if get_ipython(): # If Running With IPython, ... + connString += ";HOSTNAME=" + socket.gethostname() + connString += ";PORT=" + self.portNum + connString += ";PROTOCOL=TCPIP" + connString += ";UID=" + self.userID + connString += ";PWD=" + self.passWord + + # Otherwise, Construct The Portion Of The Connection String That Will Be Used To + # Establish A Connection To A Remote Db2 Server Or A Db2 Database + else: + connString += ";DATABASE=" + self.dbName # Only Used To Connect To A Database + connString += ";HOSTNAME=" + self.hostName # Only Used To Connect To A Server + connString += ";PORT=" + self.portNum # Only Used To Connect To A Server + connString += ";PROTOCOL=TCPIP" + connString += ";UID=" + self.userID + connString += ";PWD=" + self.passWord + + # Attempt To Establish A Connection To The Appropriate Db2 Server Or Database + # If Running With IPython (i.e., Jupyter Notebook), ... + if get_ipython(): + try: + self.connectionID = ibm_db.connect(connString, '', '') + except Exception: + pass + + # If Running With Python, ... + else: + try: + self.connectionID = ibm_db.connect(connString, self.userID, self.passWord) + except Exception: + pass + + # If A Connection Could Not Be Established, Display An Appropriate Error Message + # And Set The Function Return Code Attribute To "False" + if self.connectionID is None: + msgString = "\nERROR: Unable to connect to the " + if self.dsType is 'LOCAL_SVR': + print(msgString + "local server ... ", end="") + elif self.dsType is 'SERVER': + print(msgString + self.hostName + " server.") + else: + print(msgString + self.dbName + " database.") + msgString = ibm_db.conn_errormsg() + print(msgString + "\n") + print("Connection string used: " + connString + "\n") + self.returnCode = False + + # If A Connection Could Be Established, Complete The Status Message And Set The + # Return Code Attribute To "True" + else: + print("Done!\n") + self.returnCode = True + + #---------------------------------------------------------------------------------------------# + # FUNCTION NAME: closeConnection() # + # PURPOSE: This method attempts to close the specified Db2 server or database # + # connection. # + # PARAMETERS: None # + #---------------------------------------------------------------------------------------------# + def closeConnection(self): + """Attempt to close a Db2 server or database connection.""" + + # Define And Initialize The Appropriate Local Variables + msgString = "" + returnCode = False + + # If A Db2 Server Or Database Connection Exists, ... + if not self.connectionID is None: + + # Display An Appropriate Status Message + msgString = "Disconnecting from the " + if self.dsType is 'LOCAL_SVR': + print(msgString + "local server ... ", end="") + elif self.dsType is 'SERVER': + print(msgString + self.hostName + " server ... ", end="") + else: + print(msgString + self.dbName + " database ... ", end="") + + # Attempt To Close A Db2 Server Or Database Connection That Was Opened Earlier + try: + returnCode = ibm_db.close(self.connectionID) + except Exception: + pass + + # If The Connection Could Not Be Closed, Display An Appropriate Error Message + # And Set The Return Code Attribute To "False" + if returnCode is False: + msgString = "\nERROR: Unable to disconnect from the " + if self.dsType is 'LOCAL_SVR': + print(msgString + "local server.") + elif self.dsType is 'SERVER': + print(msgString + self.hostName + " server.") + else: + print(msgString + self.dbName + " database.") + msgString = ibm_db.conn_errormsg(self.connectionID) + print(msgString + "\n") + self.returnCode = False + + # If The Connection Could Be Closed, Complete The Status Message And Set The + # Return Code Attribute To "True" + else: + print("Done!\n") + self.returnCode = True + + +#-------------------------------------------------------------------------------------------------# +# FUNCTION NAME: get_row_count() # +# PURPOSE: This function queries the Db2 table specified and displays the number of rows # +# (records) found in it. # +# PARAMETERS: dbConnection - A valid Db2 database connection # +# tableName - Name of the table to be queried # +# RETURNS: True - A row count was obtained for the table specified # +# False - A row count could not be obtained for the table specified # +#-------------------------------------------------------------------------------------------------# +def get_row_count(dbConnection, tableName): + + # Define And Initialize The Appropriate Local Variables + resultSet = False + dataRecord = False + + # Create The SQL Statement To Be Executed + sqlStatement = "SELECT COUNT(*) FROM " + tableName + " WITH UR" + + # Execute The SQL Statement Just Defined + try: + resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement) + except Exception: + pass + + # If The SQL Statement Could Not Be Executed, Display An Error Message And Return The + # Value "False" + if resultSet is False: + print("\nERROR: Unable to execute the statement specified:") + print(" " + sqlStatement + "\n") + return False + + # Retrieve The Data Produced By The SQL Statement And Store It In A Python Tuple + try: + dataRecord = ibm_db.fetch_tuple(resultSet) + except: + pass + + # If The Data Could Not Be Retrieved, Display An Error Message And Return The Value "False" + if dataRecord is False: + print("\nERROR: Unable to retrieve the data produced by the SQL statement.") + return False + + # If The Data Could Be Retrieved, Display It + else: + print("Number of records found in the " + tableName + " table: ", end="") + print("{}\n" .format(dataRecord[0])) + + # Return The Value "True" To The Calling Function + return True + + +#-------------------------------------------------------------------------------------------------# +# FUNCTION NAME: query_sdb_dir() # +# PURPOSE: This function queries the Db2 System Database Directory and displays the # +# information obtained. # +# PARAMETERS: dbName - Name of the database to retrieve information for # +# RETURNS: True - The Db2 System Database Directory was queried successfully # +# False - Information in Db2 System Database Directory could not be obtained # +#-------------------------------------------------------------------------------------------------# +def query_sdb_dir(dbName): + + # Display An Appropriate Status Message + print("Querying the system database directory ... ", end="") + + # Retrieve The Contents Of The Db2 System Database Directory + result = subprocess.run(['db2', 'LIST DB DIRECTORY'], stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True) + + # If The Contents Of The System Database Directory Could Not Be Retrieved, Display An Error + # Message And Return The Value "False" + if result.returncode > 1: + dirInfo = str("{}".format(result.stdout)) + if not 'SQL1057W' in dirInfo: + print("\nERROR: {}".format(result.stdout)) + else: + print("Done!\n") + print("Information about the " + dbName + " database could not be found.\n") + return False + + # Otherwise, Complete The Status Message And Store The Information Retrieved In A + # String Variable + else: + print("Done!\n") + dirInfo = str("{}".format(result.stdout)) + + # If A Record For The Database Specified Cannot Be Found In Information Obtained, Display + # An Appropriate Message And Return The Value "False" + tempName = dbName + "\n" + if not tempName in dirInfo: + print("Information about the " + dbName + " database could not be found.\n") + return False + + # Otherwise, Extract The Record For The Database Specified From The System Database Directory + # Information Retrieved + else: + + # Display A Report Header + print("System Database Directory") + endingPos = dirInfo.find('Database 1 entry:') + tempStr = dirInfo[30:int(endingPos - 2)] + print(tempStr) + print("__________________________________________________________") + + # Remove All Information Found In The String That Comes Before The Record For The + # Database Specified + dbName = dbName + "\n" + startingPos = dirInfo.find(dbName) + tempStr = dirInfo[int(startingPos - 59):] + + # Remove All Information Found In The String That Comes After The Record For The + # Database Specified + tempStr = tempStr.replace('entry:', 'entry&', 1) + endingPos = tempStr.find('entry:') + endingPos -= 10 + tempStr = tempStr[:endingPos] + tempStr = tempStr.replace('entry&', 'entry:', 1) + endingPos -= 1 + while not tempStr[endingPos] is '\n': + endingPos -= 1 + dirInfo = tempStr[:endingPos] + + # Display The Record That Was Obtained For The Database Specified + print(dirInfo + "\n") + + # Return The Value "True" To The Calling Function + return True diff --git a/python_samples/Python_Examples/ibm_db/ipynb_exit.py b/python_samples/Python_Examples/ibm_db/ipynb_exit.py new file mode 100644 index 0000000..1d647b5 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/ipynb_exit.py @@ -0,0 +1,86 @@ +#-------------------------------------------------------------------------------------------------# +# NAME: ipynb_exit.py # +# # +# PURPOSE: This file contains classes and functions that allows "exit()" functionality to work # +# without raising an error or stopping the kernel when a Python application is # +# invoked from a Jupyter Notebook. # +# # +# USAGE: Add the following line of code to the beginning of a Python program: # +# # +# from ipynb_exit import exit # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose of # +# assisting you in the creation of Python applications using the ibm_db library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, + # Functions, & Methods +from io import StringIO # Implements A File-Like Class That Reads And Writes A String + # Buffer (i.e., A Memory File) +from IPython import get_ipython # Simple Function To Call To Get The Current Interactive Shell + # Instance + +#-------------------------------------------------------------------------------------------------# +# CLASS NAME: ipynb_Exit() # +# PURPOSE: This class contains attributes and methods that can be used to establish and # +# terminate a connection to a Db2 server or database. # +#-------------------------------------------------------------------------------------------------# +class ipynb_Exit(SystemExit): + """Exit Exception for IPython. Exception temporarily redirects stderr to buffer.""" + + #---------------------------------------------------------------------------------------------# + # FUNCTION NAME: __init()__ # + # PURPOSE: This method initializes an instance of the ipynb_Exit class. # + #---------------------------------------------------------------------------------------------# + def __init__(self): + sys.stderr = StringIO() # Redirect sys.stderr to a StringIO (memory buffer) object. + + #---------------------------------------------------------------------------------------------# + # FUNCTION NAME: __init()__ # + # PURPOSE: This method cleans up when an instance of the ipynb_Exit class is # + # deleted. # + #---------------------------------------------------------------------------------------------# + def __del__(self): + sys.stderr = sys.__stderr__ # Restore sys.stderr to the original values it had at + # the start of the program. + +#-------------------------------------------------------------------------------------------------# +# FUNCTION: customExit() # +# PURPOSE: This function contains attributes and methods that can be used to establish and # +# terminate a connection to a Db2 server or database. # +#-------------------------------------------------------------------------------------------------# +def customExit(returnCode=0): + if returnCode is 0: + ipynb_Exit() + else: + raise ipynb_Exit + +#-------------------------------------------------------------------------------------------------# +# If An Application Running With IPython (i.e., A Jupyter Notebook) Calls The Exit Function, # +# Call A Custom Exit Routine So The Jupyter Notebook Will Not Stop Running; Otherwise, Call The # +# Default Exit Routine # +#-------------------------------------------------------------------------------------------------# +if get_ipython(): + exit = customExit # Rebind To The Custom Exit Function +else: + exit = exit # Just Call The Exit Function diff --git a/python_samples/Python_Examples/ibm_db/readme.md b/python_samples/Python_Examples/ibm_db/readme.md new file mode 100644 index 0000000..0c8e66e --- /dev/null +++ b/python_samples/Python_Examples/ibm_db/readme.md @@ -0,0 +1,9 @@ +This directory contains example programs that illustrate how to use the APIs available with the ibm_db library to build applications that interact with Db2 (formerly DB2 for Linux, UNIX, and Windows) databases. +
    +
  1. Download the following files and copy them to the directory where the Python files you download will be stored: +
      +
    • ibm_db_tools.py
    • +
    • ipynb_exit.py
    • +
    +
  2. To execute any Python file downloaded, follow the instructions provided in the file header.
  3. +
diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-arraysize.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-arraysize.py new file mode 100644 index 0000000..674c72c --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-arraysize.py @@ -0,0 +1,158 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-arraysize.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .arraysize attribute for the # +# cursor object associated with the IBM_DBConnection object returned by the # +# ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-arraysize.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +resultSet = False +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Define The SQL Statement That Is To Be Used To Retrieve Data From The PROJECT Table +sqlStatement = "SELECT projno, projname FROM project ORDER BY projno" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = cursorID.execute(sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Set The arraysize Attribute Of The Current Cursor To Control How Many Rows Will Be +# Retrieved At One Time When The .fetchmany() Function Is Called. +try: + cursorID.arraysize = 4 +except Exception: + print("\nERROR: Unable to set the arraysize cursor attribute.") + connectionID.close() + exit(-1) + +# Retrieve The Appropriate Number Of Records From The Last Result Set Returned And Store +# Them In A Python Tuple +print("Retrieving the first " + str(cursorID.arraysize) + " values returned ", end="") +print("by the SQL statement ... ", end="") +try: + resultSet = cursorID.fetchmany() +except: + pass + +# If The Results Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is None: + print("\nERROR: Unable to obtain the results desired.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("PROJNO PROJNAME") +print("______ _____________________") + +# As Long As There Are Records In The Result Set Produced, Print Them +for result in resultSet: + print("{:<6} {:24}" .format(result[0], result[1])) + +# Add A Blank Line To The End Of The Report +print() + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-callproc.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-callproc.py new file mode 100644 index 0000000..2b86841 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-callproc.py @@ -0,0 +1,159 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-callproc.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .callproc() function of the # +# cursor object associated with the IBM_DBConnection object returned by the # +# ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-callproc.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +spName = "SALARY_STATS" +returnCode = False +spParamValues = (0.0, 0.0, 0.0) +resultSet = None + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Define The SQL Statement That Is To Be Used To Create A New Stored Procedure +sqlStatement = "CREATE OR REPLACE PROCEDURE " + spName +sqlStatement += " (OUT maxSalary DOUBLE, OUT minSalary DOUBLE, OUT avgSalary DOUBLE) " +sqlStatement += "LANGUAGE SQL " +sqlStatement += "DYNAMIC RESULT SETS 0 " +sqlStatement += "READS SQL DATA " +sqlStatement += "NO EXTERNAL ACTION " +sqlStatement += "BEGIN" +sqlStatement += " SELECT MAX(salary) INTO maxSalary FROM employee; " +sqlStatement += " SELECT MIN(salary) INTO minSalary FROM employee; " +sqlStatement += " SELECT AVG(salary) INTO avgSalary FROM employee; " +sqlStatement += "END" + +# Execute The SQL Statement Just Defined +print("Creating an SQL stored procedure named \"" + spName + "\" ... ", end="") +try: + resultSet = cursorID.execute(sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Execute The Stored Procedure Just Created +print("Executing the " + spName + " stored procedure ... ", end="") +try: + resultSet = cursorID.callproc(spName, spParamValues) +except Exception: + pass + +# If The Stored Procedure Specified Could Not Be Executed, Display An Error Message And Exit +if resultSet is None: + print("\nERROR: Unable to execute the stored procedure specified.") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message; Then Format And Display The Data Values Returned +else: + print("Done!\n") + + # Display A Report Header + print("Salary statistics:") + print("______________________________") + + # Display The Data Values Returned By The Stored Procedure + print("Highest salary : ${:>10.2f}" .format(resultSet[0])) + print("Lowest salary : ${:>10.2f}" .format(resultSet[1])) + print("Average salary : ${:>10.2f}" .format(resultSet[2])) + +# Add A Blank Line To The End Of The Report +print() + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-close_CONNECTION.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-close_CONNECTION.py new file mode 100644 index 0000000..89bbf95 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-close_CONNECTION.py @@ -0,0 +1,96 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-close_CONNECTION.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .close() function of the # +# IBM_DBConnection object that is returned by the ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-close_CONNECTION.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + + +# Add Additional Processing Here ... + + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-close_CURSOR.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-close_CURSOR.py new file mode 100644 index 0000000..e9d4bc5 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-close_CURSOR.py @@ -0,0 +1,157 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-close_CURSOR.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .close() function of the # +# cursor object associated with the IBM_DBConnection object returned by the # +# ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-close_CURSOR.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Define The SQL Statement That Is To Be Used To Retrieve Data From The PROJECT Table +sqlStatement = "SELECT projno, projname FROM project WHERE prstaff < 2" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = cursorID.execute(sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve All Of The Records Returned And Store Them In A Python Tuple +print("Retrieving all of the values returned by the SQL statement just executed ... ", end="") +try: + resultSet = cursorID.fetchall() +except: + pass + +# If The Results Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is None: + print("\nERROR: Unable to obtain the results desired.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("PROJNO PROJNAME") +print("______ _____________________") + +# As Long As There Are Records In The Result Set Produced, Print Them +for result in resultSet: + print("{:<6} {:24}" .format(result[0], result[1])) + +# Add A Blank Line To The End Of The Report +print() + +# Close The Cursor Since It Is No Longer Needed; If An Error Occurs, Display An Error +# Message And Continue +print("Closing the cursor used ... ", end="") +try: + cursorID.close() +except Exception: + print("\nERROR: Unable to close the cursor.") + +# Otherwise, Complete The Status Message +print("Done!\n") + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-commit.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-commit.py new file mode 100644 index 0000000..cc3415c --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-commit.py @@ -0,0 +1,167 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-commit.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .commit() function of the # +# IBM_DBConnection object that is returned by the ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-rollback.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The get_row_count() Function That Has Been Defined In The File Named # +# "ibm_db_dbi_tools.py"; This Function Contains The Programming Logic Needed To Obtain And # +# Display The Number Of Rows (Records) Found In A Db2 Database Table. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_dbi_tools import get_row_count + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +resultSet = False +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table +returnCode = get_row_count(cursorID, 'DEPARTMENT') +if returnCode is False: + if not connectionID is None: + connectionID.close() + exit(-1) + +# Define The INSERT Statement That Is To Be Used To Add Data To The DEPARTMENT Table +sqlStatement = "INSERT INTO department VALUES('K01', 'SALES', '000130', 'K01', NULL)" + +# Execute The SQL Statement Just Defined +print("Inserting a record into the DEPARTMENT table ... ", end="") +try: + resultSet = cursorID.execute(sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the INSERT statement specified.") + if not connectionID is None: + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display The Number Of Rows That Exist In The DEPARTMENT Table Now +# (The Number Returned Should Change) +returnCode = get_row_count(cursorID, 'DEPARTMENT') +if returnCode is False: + if not connectionID is None: + connectionID.close() + exit(-1) + +# Commit The Changes Just Made To The Database +print("Commiting changes made to the database ... ", end="") +resultSet = False +try: + resultSet = connectionID.commit() +except Exception: + pass + +# If The Commit Operation Could Not Be Performed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to roll back the previous operation.") + if not connectionID is None: + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display The Number Of Rows That Exist In The DEPARTMENT Table Now +# (The Number Should Not Change) +returnCode = get_row_count(cursorID, 'DEPARTMENT') +if returnCode is False: + if not connectionID is None: + connectionID.close() + exit(-1) + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-connect_DB.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-connect_DB.py new file mode 100644 index 0000000..c6a82a9 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-connect_DB.py @@ -0,0 +1,96 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-connect_DB.py # +# # +# PURPOSE: This program is designed to illustrate how to use the ibm_db_dbi.connect() API to # +# establish a connection to a local Db2 database. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-connect_DB.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + + +# Add Additional Processing Here ... + + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-cursor.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-cursor.py new file mode 100644 index 0000000..b97ea5f --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-cursor.py @@ -0,0 +1,102 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-cursor.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .cursor() function of the # +# IBM_DBConnection object that is returned by the ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-cursor.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# If The Cursor Object Was Successfully Retrieved, Display Information About The Cursor Handler +if not cursorID is None: + print("Cursor connection handler: ", end="") + print(cursorID.conn_handler) + print() + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-description.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-description.py new file mode 100644 index 0000000..d2056d3 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-description.py @@ -0,0 +1,176 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-description.py # +# # +# PURPOSE: This program is designed to illustrate how to display the .description attribute # +# information for the cursor object associated with the IBM_DBConnection object # +# returned by the ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-description.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +resultSet = False +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Define The SQL Statement That Is To Be Used To Retrieve Data From The EMPLOYEE Table +sqlStatement = "SELECT empno, salary FROM employee" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = cursorID.execute(sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve Attribute Information For Every Column In The Result Set Produced By The SQL Statement +# Just Executed +cursorInfo = cursorID.description + +# Display A Report Header +print("Cursor result column information:\n") + +# As Long As There Are Records, ... +loopCounter = 0 +for dataRecord in cursorInfo: + + # Extract All Data Stored In The Current Column Attribute Variable + columnName = cursorInfo[loopCounter][0] + dataTypes = cursorInfo[loopCounter][1] + typeNames = [] + for type in dataTypes: + typeNames.append(type) + displaySize = cursorInfo[loopCounter][2] + internalSize = cursorInfo[loopCounter][3] + precision = cursorInfo[loopCounter][4] + scale = cursorInfo[loopCounter][5] + nullable = cursorInfo[loopCounter][6] + + # Display Record Header Information + print("Column " + str(loopCounter + 1) + " details:") + print("____________________________________________") + + # Display The Information Stored In The Data Record Retrieved + print("Column name : {}" .format(columnName)) + print("Data type name(s) : ", end="") + print(typeNames[0]) + del typeNames[0] + for type in typeNames: + print(' ' * 27, end="") + print("{}" .format(type)) + print("Display size : {}" .format(displaySize)) + print("Internal size : {}" .format(internalSize)) + print("Precision : {}" .format(precision)) + print("Scale (decimal digits) : {}" .format(scale)) + print("Can accept NULL values : ", end="") + if nullable == True: + print("YES") + else: + print("NO") + + # Increment The loopCounter Variable And Print A Blank Line To Separate The + # Records From Each Other + loopCounter += 1 + print() + +# Close The Cursor Since It Is No Longer Needed +try: + cursorID.close() +except Exception: + print("\nERROR: Unable to close the cursor.") + connectionID.close() + exit(-1) + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-execute.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-execute.py new file mode 100644 index 0000000..d03a9f3 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-execute.py @@ -0,0 +1,147 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-execute.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .execute() function of the # +# cursor object associated with the IBM_DBConnection object returned by the # +# ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-execute.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +resultSet = False +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Define The SQL Statement That Is To Be Used To Retrieve Data From The PROJECT Table +sqlStatement = "SELECT projno, projname FROM project WHERE prstaff < 2" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = cursorID.execute(sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve All Of The Records Returned And Store Them In A Python Tuple +print("Retrieving all of the values returned by the SQL statement just executed ... ", end="") +try: + resultSet = cursorID.fetchall() +except: + pass + +# If The Results Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is None: + print("\nERROR: Unable to obtain the results desired.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("PROJNO PROJNAME") +print("______ _____________________") + +# As Long As There Are Records In The Result Set Produced, Print Them +for result in resultSet: + print("{:<6} {:24}" .format(result[0], result[1])) + +# Add A Blank Line To The End Of The Report +print() + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-executemany.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-executemany.py new file mode 100644 index 0000000..eaa6f3c --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-executemany.py @@ -0,0 +1,149 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-executemany.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .executemany() function of # +# the cursor object associated with the IBM_DBConnection object returned by the # +# ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-executemany.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The get_row_count() Function That Has Been Defined In The File Named # +# "ibm_db_dbi_tools.py"; This Function Contains The Programming Logic Needed To Obtain And # +# Display The Number Of Rows (Records) Found In A Db2 Database Table. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_dbi_tools import get_row_count + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +resultSet = False +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table +returnCode = get_row_count(cursorID, 'DEPARTMENT') +if returnCode is False: + if not connectionID is None: + connectionID.close() + exit(-1) + +# Define The INSERT Statement (With Parameter Markers) That Is To Be Used To Add Data +# To The DEPARTMENT Table +sqlStatement = "INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)" + +# Create A List Of Data Values That Are To Be Supplied For The Parameter Markers Coded +# In The INSERT Statement Specified +pmValues = (('K22', 'SALES', '000110'), + ('L22', 'FINANCE', '000120'), + ('M22', 'HUMAN RESOURCES', '000130')) + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = cursorID.executemany(sqlStatement, pmValues) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message And Display The Number Of Records Added +else: + rowsAffected = cursorID.rowcount + print("Done!\n") + print("Number of records added : {}\n" .format(rowsAffected)) + +# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table +# (The Number Returned Should Change By Three) +returnCode = get_row_count(cursorID, 'DEPARTMENT') +if returnCode is False: + if not connectionID is None: + connectionID.close() + exit(-1) + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchall.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchall.py new file mode 100644 index 0000000..f179295 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchall.py @@ -0,0 +1,147 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-fetchall.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .fetchall() function of the # +# cursor object associated with the IBM_DBConnection object returned by the # +# ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-fetchall.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +resultSet = False +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Define The SQL Statement That Is To Be Used To Retrieve Data From The PROJECT Table +sqlStatement = "SELECT projno, projname FROM project" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = cursorID.execute(sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve All Of The Records Returned And Store Them In A Python Tuple +print("Retrieving all of the values returned by the SQL statement just executed ... ", end="") +try: + resultSet = cursorID.fetchall() +except: + pass + +# If The Results Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is None: + print("\nERROR: Unable to obtain the results desired.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("PROJNO PROJNAME") +print("______ _____________________") + +# As Long As There Are Records In The Result Set Produced, Print Them +for result in resultSet: + print("{:<6} {:24}" .format(result[0], result[1])) + +# Add A Blank Line To The End Of The Report +print() + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchmany.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchmany.py new file mode 100644 index 0000000..5be0b3d --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchmany.py @@ -0,0 +1,147 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-fetchmany.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .fetchmany() function of the # +# cursor object associated with the IBM_DBConnection object returned by the # +# ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-fetchmany.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +resultSet = False +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Define The SQL Statement That Is To Be Used To Retrieve Data From The PROJECT Table +sqlStatement = "SELECT projno, projname FROM project ORDER BY projno" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = cursorID.execute(sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The First Five Records Returned And Store Them In A Python Tuple +print("Retrieving the first five values returned by the SQL statement ... ", end="") +try: + resultSet = cursorID.fetchmany(5) +except: + pass + +# If The Results Could Not Be Retrieved, Display An Error Message And Exit +if resultSet is None: + print("\nERROR: Unable to obtain the results desired.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("PROJNO PROJNAME") +print("______ _____________________") + +# As Long As There Are Records In The Result Set Produced, Print Them +for result in resultSet: + print("{:<6} {:24}" .format(result[0], result[1])) + +# Add A Blank Line To The End Of The Report +print() + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchone.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchone.py new file mode 100644 index 0000000..8c6d91c --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-fetchone.py @@ -0,0 +1,145 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-fetchone.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .fetchone() function of the # +# cursor object associated with the IBM_DBConnection object returned by the # +# ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-fetchone.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +resultSet = False +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Define The SQL Statement That Is To Be Used To Retrieve Data From The PROJECT Table +sqlStatement = "SELECT projno, projname FROM project WHERE prstaff < 2" + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = cursorID.execute(sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Query results:\n") +print("PROJNO PROJNAME") +print("______ _____________________") + +# As Long As There Are Records In The Result Set Produced, ... +noData = False +while noData is False: + + # Retrieve A Record And Store It In A Python Tuple + try: + resultSet = cursorID.fetchone() + except: + pass + + # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Set The + # "No Data" Flag And Exit The Loop + if resultSet is None: + noData = True + + # Otherwise, Display The Data Retrieved + else: + print("{:<6} {:24}" .format(resultSet[0], resultSet[1])) + +# Add A Blank Line To The End Of The Report +print() + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-nextset.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-nextset.py new file mode 100644 index 0000000..f4fae96 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-nextset.py @@ -0,0 +1,270 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-nextset.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .nextset() function of the # +# cursor object associated with the IBM_DBConnection object returned by the # +# ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-nextset.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +spName = "HIGH_EARNERS" +returnCode = False +dataRecords = None + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Define The SQL Statement That Is To Be Used To Create A New Stored Procedure That +# Returns Three Result Sets +sqlStatement = "CREATE OR REPLACE PROCEDURE " + spName + " " +sqlStatement += "LANGUAGE SQL " +sqlStatement += "DYNAMIC RESULT SETS 3 " +sqlStatement += "READS SQL DATA " +sqlStatement += "NO EXTERNAL ACTION " +sqlStatement += "BEGIN " +sqlStatement += " DECLARE avgSalary INT DEFAULT 0; " +sqlStatement += " DECLARE c1 CURSOR WITH RETURN FOR " +sqlStatement += " SELECT firstnme, lastname, salary, job FROM employee " +sqlStatement += " WHERE job = 'DESIGNER' AND " +sqlStatement += " salary > avgSalary " +sqlStatement += " ORDER BY salary DESC; " +sqlStatement += " DECLARE c2 CURSOR WITH RETURN FOR " +sqlStatement += " SELECT firstnme, lastname, salary, job FROM employee " +sqlStatement += " WHERE job = 'ANALYST' AND " +sqlStatement += " salary > avgSalary " +sqlStatement += " ORDER BY salary DESC; " +sqlStatement += " DECLARE c3 CURSOR WITH RETURN FOR " +sqlStatement += " SELECT firstnme, lastname, salary, job FROM employee " +sqlStatement += " WHERE job = 'SALESREP' AND " +sqlStatement += " salary > avgSalary " +sqlStatement += " ORDER BY salary DESC; " +sqlStatement += " SELECT INT(AVG(salary)) INTO avgSalary FROM employee; " +sqlStatement += " OPEN c1; " +sqlStatement += " OPEN c2; " +sqlStatement += " OPEN c3; " +sqlStatement += "END" + +# Execute The SQL Statement Just Defined +print("Creating an SQL stored procedure named \"" + spName + "\" ... ", end="") +try: + resultSet = cursorID.execute(sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is None: + print("\nERROR: Unable to execute the SQL statement specified.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Execute The Stored Procedure Just Created +print("Executing the " + spName + " stored procedure ... ", end="") +try: + cursorID.callproc(spName, None) + +# If The Stored Procedure Specified Could Not Be Executed, Display An Error Message And Exit +except Exception: + print("\nERROR: Unable to execute the stored procedure specified.") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +print("Done!\n") + +# Retrieve The First Result Set From The Stored Procedure Just Executed +print("Retrieving the first result set produced by the " + spName, end="") +print(" procedure ... ", end="") +resultSet_1 = None +try: + resultSet_1 = cursorID.fetchall() +except Exception: + pass + +# If The First Result Set Could Not Be Retrieved, Display An Error Message And Exit +if resultSet_1 is None: + print("\nERROR: Unable to retrieve the first result set returned by the stored procedure.") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Second Result Set From The Stored Procedure Just Executed +print("Retrieving the second result set produced by the " + spName, end="") +print(" procedure ... ", end="") +resultSet_2 = None +cursorID.nextset() +try: + resultSet_2 = cursorID.fetchall() +except Exception: + pass + +# If The Second Result Set Could Not Be Retrieved, Display An Error Message And Exit +if resultSet_2 is None: + print("\nERROR: Unable to retrieve the second result set returned by the stored procedure.") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Third Result Set From The Stored Procedure Just Executed +print("Retrieving the third result set produced by the " + spName, end="") +print(" procedure ... ", end="") +resultSet_3 = None +cursorID.nextset() +try: + resultSet_3 = cursorID.fetchall() +except Exception: + pass + +# If The Third Result Set Could Not Be Retrieved, Display An Error Message And Exit +if resultSet_3 is False: + print("\nERROR: Unable to retrieve the third result set returned by the stored procedure.") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display A Report Header +print("Information retrieved:") + +# As Long As There Are Records To Retrieve, ... +noData = False +loopCounter = 1 +printHeader = True +dataRecord = True +while noData is False: + + # Display Record Header Information + if printHeader is True: + print("\n Result set " + str(loopCounter) + " details:\n") + print(" FIRSTNME LASTNAME SALARY JOB") + print(" ______________ __________________ __________ ________") + printHeader = False + + # Print The Records In The Appropriate Result Set + if loopCounter is 1: + for dataRecord in resultSet_1: + print(" {:<14}" .format(dataRecord[0]), end="") + print(" {:<18}" .format(dataRecord[1]), end="") + print(" ${:>9}" .format(dataRecord[2]), end="") + print(" {:<10}" .format(dataRecord[3])) + elif loopCounter is 2: + for dataRecord in resultSet_2: + print(" {:<14}" .format(dataRecord[0]), end="") + print(" {:<18}" .format(dataRecord[1]), end="") + print(" ${:>9}" .format(dataRecord[2]), end="") + print(" {:<10}" .format(dataRecord[3])) + elif loopCounter is 3: + for dataRecord in resultSet_3: + print(" {:<14}" .format(dataRecord[0]), end="") + print(" {:<18}" .format(dataRecord[1]), end="") + print(" ${:>9}" .format(dataRecord[2]), end="") + print(" {:<10}" .format(dataRecord[3])) + + # Increment The Loop Counter Variable And Set The Appropriate Variables To True + loopCounter += 1 + printHeader = True + dataRecord = True + + # If There Is No More Data To Retrieve, Set The "No Data" Flag And Exit The Loop + if loopCounter is 4: + noData = True + else: + continue + +# Add A Blank Line To The End Of The Report +print() + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-rollback.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-rollback.py new file mode 100644 index 0000000..79a2c4c --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-rollback.py @@ -0,0 +1,167 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-rollback.py # +# # +# PURPOSE: This program is designed to illustrate how to use the .rollback() function of the # +# IBM_DBConnection object that is returned by the ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-rollback.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# Import The get_row_count() Function That Has Been Defined In The File Named # +# "ibm_db_dbi_tools.py"; This Function Contains The Programming Logic Needed To Obtain And # +# Display The Number Of Rows (Records) Found In A Db2 Database Table. # +#-------------------------------------------------------------------------------------------------# +from ibm_db_dbi_tools import get_row_count + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +resultSet = False +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Display The Number Of Rows That Currently Exist In The DEPARTMENT Table +returnCode = get_row_count(cursorID, 'DEPARTMENT') +if returnCode is False: + if not connectionID is None: + connectionID.close() + exit(-1) + +# Define The INSERT Statement That Is To Be Used To Add Data To The DEPARTMENT Table +sqlStatement = "INSERT INTO department VALUES('K01', 'SALES', '000130', 'K01', NULL)" + +# Execute The SQL Statement Just Defined +print("Inserting a record into the DEPARTMENT table ... ", end="") +try: + resultSet = cursorID.execute(sqlStatement) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the INSERT statement specified.") + if not connectionID is None: + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display The Number Of Rows That Exist In The DEPARTMENT Table Now +# (The Number Returned Should Change) +returnCode = get_row_count(cursorID, 'DEPARTMENT') +if returnCode is False: + if not connectionID is None: + connectionID.close() + exit(-1) + +# Back Out The Changes Just Made To The Database +print("Backing out changes made to the database ... ", end="") +resultSet = False +try: + resultSet = connectionID.rollback() +except Exception: + pass + +# If The Rollback Operation Could Not Be Performed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to roll back the previous operation.") + if not connectionID is None: + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Display The Number Of Rows That Exist In The DEPARTMENT Table Now +# (The Number Should Revert Back To The Original Value) +returnCode = get_row_count(cursorID, 'DEPARTMENT') +if returnCode is False: + if not connectionID is None: + connectionID.close() + exit(-1) + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-rowcount.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-rowcount.py new file mode 100644 index 0000000..efe88db --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi-rowcount.py @@ -0,0 +1,127 @@ +#! /usr/bin/python3 +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_dbi-rowcount.py # +# # +# PURPOSE: This program is designed to illustrate how to display the .rowcount attribute # +# information for the cursor object associated with the IBM_DBConnection object # +# returned by the ibm_db_dbi.connect() API. # +# # +# USAGE: Log in as a Db2 database instance user (for example, db2inst1) and issue the # +# following command from a terminal window: # +# # +# ./ibm_db_dbi-rowcount.py # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose # +# of assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +# Define And Initialize The Appropriate Variables +dbName = "SAMPLE" # The Alias For The Cataloged, Local Database +userID = "db2inst1" # The Instance User ID At The Local Server +passWord = "Passw0rd" # The Password For The Instance User ID At The Local Server +connectionID = None +resultSet = False +returnCode = False + +# Display A Status Message Indicating An Attempt To Establish A Connection To A Db2 Database +# Is About To Be Made +print("\nConnecting to the \'" + dbName + "\' database ... ", end="") + +# Construct The String That Will Be Used To Establish A Db2 Database Connection +connString = "ATTACH=FALSE" # Attach To A Database; Not A Server +connString += ";DATABASE=" + dbName # Required To Connect To A Database +connString += ";PROTOCOL=TCPIP" +connString += ";UID=" + userID +connString += ";PWD=" + passWord + +# Attempt To Establish A Connection To The Database Specified +try: + connectionID = ibm_db_dbi.connect(connString, '', '') +except Exception: + pass + +# If A Db2 Database Connection Could Not Be Established, Display An Error Message And Exit +if connectionID is None: + print("\nERROR: Unable to connect to the \'" + dbName + "\' database.") + print("Connection string used: " + connString + "\n") + exit(-1) + +# Otherwise, Complete The Status Message +else: + print("Done!\n") + +# Retrieve The Cursor Object That Was Created For The Connection Object +if not connectionID is None: + cursorID = connectionID.cursor() + +# Define The INSERT Statement (With Parameter Markers) That Is To Be Used To Add Data +# To The DEPARTMENT Table +sqlStatement = "INSERT INTO department VALUES(?, ?, ?, 'E01', NULL)" + +# Create A List Of Data Values That Are To Be Supplied For The Parameter Markers Coded +# In The INSERT Statement Specified +pmValues = (('K22', 'SALES', '000110'), + ('L22', 'FINANCE', '000120'), + ('M22', 'HUMAN RESOURCES', '000130')) + +# Execute The SQL Statement Just Defined +print("Executing the SQL statement \"" + sqlStatement + "\" ... ", end="") +try: + resultSet = cursorID.executemany(sqlStatement, pmValues) +except Exception: + pass + +# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit +if resultSet is False: + print("\nERROR: Unable to execute the SQL statement specified.\n") + connectionID.close() + exit(-1) + +# Otherwise, Complete The Status Message And Display The Number Of Records Added +else: + rowsAffected = cursorID.rowcount + print("Done!\n") + print("Number of records added : {}\n" .format(rowsAffected)) + +# Attempt To Close The Db2 Database Connection That Was Opened Earlier +if not connectionID is None: + print("Disconnecting from the \'" + dbName + "\' database ... ", end="") + try: + returnCode = connectionID.close() + except Exception: + pass + + # If The Db2 Database Connection Was Not Closed, Display An Error Message And Exit + if returnCode is False: + print("\nERROR: Unable to disconnect from the " + dbName + " database.") + exit(-1) + + # Otherwise, Complete The Status Message + else: + print("Done!\n") + +# Return Control To The Operating System +exit() diff --git a/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi_tools.py b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi_tools.py new file mode 100644 index 0000000..fc0d7bb --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/ibm_db_dbi_tools.py @@ -0,0 +1,90 @@ +#-------------------------------------------------------------------------------------------------# +# NAME: ibm_db_tools.py # +# # +# PURPOSE: This file contains classes and functions that are used by some of the ibm_db_dbi # +# sample programs. # +# # +# Cursor functions used: # +# execute() # +# fetchone() # +# # +# USAGE: Add the following line of code at the beginning of an ibm_db_dbi sample program: # +# # +# from ibm_db_dbi_tools import get_row_count # +# # +#-------------------------------------------------------------------------------------------------# +# DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITY # +# # +# (C) COPYRIGHT International Business Machines Corp. 2018, 2019 All Rights Reserved # +# Licensed Materials - Property of IBM # +# # +# US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP # +# Schedule Contract with IBM Corp. # +# # +# The following source code ("Sample") is owned by International Business Machines Corporation # +# or one of its subsidiaries ("IBM") and is copyrighted and licensed, not sold. You may use, # +# copy, modify, and distribute the Sample in any form without payment to IBM, for the purpose of # +# assisting you in the creation of Python applications using the ibm_db_dbi library. # +# # +# The Sample code is provided to you on an "AS IS" basis, without warranty of any kind. IBM # +# HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT # +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # +# Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the # +# above limitations or exclusions may not apply to you. IBM shall not be liable for any damages # +# you suffer as a result of using, copying, modifying or distributing the Sample, even if IBM # +# has been advised of the possibility of such damages. # +#-------------------------------------------------------------------------------------------------# + +# Load The Appropriate Python Modules +import sys # Provides Information About Python Interpreter Constants, Functions, & Methods +import ibm_db_dbi # Contains The APIs Needed To Work With Db2 Databases + +#-------------------------------------------------------------------------------------------------# +# FUNCTION NAME: get_row_count() # +# PURPOSE: This function queries the Db2 table specified and displays the number of rows # +# (records) found in it. # +# PARAMETERS: dbCursor - A cursor object associated with a valid Db2 database connection # +# tableName - Name of the table to be queried # +# RETURNS: True - A row count was obtained for the table specified # +# False - A row count could not be obtained for the table specified # +#-------------------------------------------------------------------------------------------------# +def get_row_count(dbCursor, tableName): + + # Define And Initialize The Appropriate Local Variables + resultSet = False + + # Create The SQL Statement To Be Executed + sqlStatement = "SELECT COUNT(*) FROM " + tableName + " WITH UR" + + # Execute The SQL Statement Just Defined + try: + resultSet = dbCursor.execute(sqlStatement) + except Exception: + pass + + # If The SQL Statement Could Not Be Executed, Display An Error Message And Exit + if resultSet is False: + print("\nERROR: Unable to execute the statement specified:") + print(" " + sqlStatement + "\n") + return False + + # Retrieve The Data Produced By The SQL Statement And Store It In A Python Tuple + resultSet = None + try: + resultSet = dbCursor.fetchone() + except: + pass + + # If The Data Could Not Be Retrieved Or There Was No Data To Retrieve, Display An Error + # Message And Return The Value "False" + if resultSet is None: + print("\nERROR: Unable to retrieve the data produced by the SQL statement.") + return False + + # Otherwise, Display The Data Retrieved + else: + print("Number of records found in the " + tableName + " table: ", end="") + print("{}\n" .format(resultSet[0])) + + # Return The Value "True" To The Calling Function + return True diff --git a/python_samples/Python_Examples/ibm_db_dbi/readme.md b/python_samples/Python_Examples/ibm_db_dbi/readme.md new file mode 100644 index 0000000..e05ffd7 --- /dev/null +++ b/python_samples/Python_Examples/ibm_db_dbi/readme.md @@ -0,0 +1,9 @@ +This directory contains example programs that illustrate how to use the APIs available with the ibm_db_dbi library to build applications that interact with Db2 (formerly DB2 for Linux, UNIX, and Windows) databases. +
    +
  1. Download the following file and copy it to the directory where the Python files you download will be stored: +
      +
    • ibm_db_dbi_tools.py
    • +
    +
  2. To execute any Python file downloaded, follow the instructions provided in the file header.
  3. +
+ diff --git a/python_samples/Python_Examples/readme.md b/python_samples/Python_Examples/readme.md new file mode 100644 index 0000000..45690b0 --- /dev/null +++ b/python_samples/Python_Examples/readme.md @@ -0,0 +1 @@ +Example programs that illustrate how to use the APIs available with the ibm_db library can be found in the ibm_db directory; examples that show how to use the APIs and functions available with the ibm_db_dbi library can be found in the ibm_db_dbi directory. diff --git a/python_samples/README.md b/python_samples/README.md new file mode 100644 index 0000000..ecc1365 --- /dev/null +++ b/python_samples/README.md @@ -0,0 +1,59 @@ +# db2-python +This repository contains Jupyter Notebooks and Python sample programs that illustrate how to use the APIs that are available in the ibm_db and ibm_db_dbi library with Db2. The list of APIs available with the ibm_db library are: + + + +For information on how to use the APIs and functions in the ibm_db_dbi library, refer to the PEP 249 -- Python Database API Specification v2.0. diff --git a/python_samples/_config.yml b/python_samples/_config.yml new file mode 100644 index 0000000..2f7efbe --- /dev/null +++ b/python_samples/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-minimal \ No newline at end of file