<jupyter_start><jupyter_text>ibm_db.connect()  Purpose: Establish a new connection to an IBM Db2 server or database.  Syntax: `IBM_DBConnection ibm_db.connect( string `*`connectionInfo,`*` string `*`userID,`*` string `*`userPassword`*` [, dictionary `*`options`*` [, constant `*`replaceQuotedLiterals`*` ] ] )`  Parameters: * __*connectionInfo*__&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : 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`&nbsp; &nbsp; &nbsp;: 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`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;: 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`&nbsp; &nbsp; &nbsp;: 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`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;: 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`&nbsp; &nbsp; &nbsp;: The user name/ID that is to be used for authentication when the connection is established.    * `password`&nbsp; &nbsp; &nbsp;: The password that corresponds to the user name/ID specified in the __*userName*__ parameter.               * __*userID*__&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;: 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*__&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : 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*__&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;: 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`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;: 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`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;: 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`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;: 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`&nbsp; &nbsp;: 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*__&nbsp; &nbsp; : Identifies whether quotes are allowed around literal values. Valid values for this parameter are:        * `ibm_db.QUOTED_LITERAL_REPLACEMENT_ON`&nbsp; &nbsp; &nbsp;: 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`&nbsp; &nbsp;: 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 &mdash; for example, __conn = ibm_db.connect( 'SAMPLE', ' ', ' ' )__, &mdash; 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:  &nbsp; Example 1: Connect to a local, cataloged Db2 database<jupyter_code>#----------------------------------------------------------------------------------------------#
#  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 = "<PASSWORD>"    # 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()<jupyter_output>Connecting to the 'SAMPLE' database ... Done!

Executing the SQL statement "SELECT deptname FROM org WHERE deptnumb = '50000'" ... Done!

Disconnecting from the 'SAMPLE' database ... Done!<jupyter_text>&nbsp; Example 2: Connect to a remote Db2 server<jupyter_code>#----------------------------------------------------------------------------------------------#
#  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 = "172.16.31.10"    # 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 = "<PASSWORD>"           # 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()<jupyter_output>Connecting to the '172.16.31.10' server ... Done!

Disconnecting from the '172.16.31.10' server ... Done!
{'fraction_non_alphanumeric': 0.11901336073997945, 'fraction_numerical': 0.006474820143884892, 'mean_word_length': 1.9094034982807595, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 3, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 90, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '319897', 'license': 'Apache-2.0', 'n_tokens_mistral': 4731, 'n_tokens_neox': 4549, 'n_words': 2069, 'path': 'python_samples/Jupyter_Notebooks/ibm_db-connect.ipynb', 'repo_name': 'dapper-hacker/db2-samples', 'size': '19457'}