Example: Initialization and connection in a DB2® UDB CLI application

Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
/*******************************************************
** file = basiccon.c
**    - demonstrate basic connection to two datasources.
**    - error handling  ignored for simplicity
**
**  Functions used:
**
**    SQLAllocConnect  SQLDisconnect
**    SQLAllocEnv      SQLFreeConnect
**    SQLConnect       SQLFreeEnv
**
**
********************************************************/
 
#include <stdio.h>
#include <stdlib.h>
#include "sqlcli.h"
 
int
connect(SQLHENV henv,
        SQLHDBC * hdbc);
 
#define MAX_DSN_LENGTH    18
#define MAX_UID_LENGTH    10
#define MAX_PWD_LENGTH    10
#define MAX_CONNECTIONS   5
 
int
main()
{
    SQLHENV         henv;
    SQLHDBC         hdbc[MAX_CONNECTIONS];
 
    /* allocate an environment handle   */
    SQLAllocEnv(&henv);
 
    /* Connect to first data source */
    connect(henv, &hdbc[0];);
 
    /* Connect to second data source */
    connect(henv, &hdbc[1];);
 
    /*********   Start Processing Step  *************************/
    /* allocate statement handle, execute statement, and so forth       */
    /*********   End Processing Step  ***************************/
 
    printf("\nDisconnecting .....\n");
    SQLDisconnect(hdbc[0]);     /* disconnect first connection   */
    SQLDisconnect(hdbc[1]);     /* disconnect second connection  */
    SQLFreeConnect(hdbc[0]);    /* free first connection handle  */
    SQLFreeConnect(hdbc[1]);    /* free second connection handle */
    SQLFreeEnv(henv);           /* free environment handle       */
 
    return (SQL_SUCCESS);
}
 
/********************************************************************
**   connect - Prompt for connect options and connect              **
********************************************************************/
 
int
connect(SQLHENV henv,
        SQLHDBC * hdbc)
{
    SQLRETURN       rc;
    SQLCHAR         server[MAX_DSN_LENGTH + 1], uid[MAX_UID_LENGTH + 1],
pwd[MAX_PWD_LENGTH
+ 1];
    SQLCHAR         buffer[255];
    SQLSMALLINT     outlen;
 
    printf("Enter Server Name:\n");
    gets((char *) server);
    printf("Enter User Name:\n");
    gets((char *) uid);
    printf("Enter Password Name:\n");
    gets((char *) pwd);
 
    SQLAllocConnect(henv, hdbc);/* allocate a connection handle     */
 
    rc = SQLConnect(*hdbc, server, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);
    if (rc != SQL_SUCCESS) {
        printf("Error while connecting to database\n");
        return (SQL_ERROR);
    } else {
        printf("Successful Connect\n");
        return (SQL_SUCCESS);
    }
}