Establishing an ODBC Connection

Establish a connection for your application, before it can carry out any database operations.

  1. Allocate an ODBC environment:
    SQLHENV env; 
    SQLRETURN retcode; 
    retcode = SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env );
  2. Declare the ODBC version.

    By declaring that the application follows ODBC version 3, SQLSTATE values and some other version-dependent features are set to the proper behavior.

    For example:

    retcode = SQLSetEnvAttr( env, SQL_ATTR_ODBC_VERSION,
       (void*)SQL_OV_ODBC3, 0);
  3. If necessary, assemble the datasource or connection string.

    Depending on your application, you can have a hard-coded datasource or connection string, or you can store it externally for greater flexibility.

  4. Allocate an ODBC connection handle:
    retcode = SQLAllocHandle( SQL_HANDLE_DBC, env, &dbc );
  5. Before connecting, set any connection attributes that are required.

    Some connection attributes must be set before establishing a connection, while others can be set either before or after.

    For example:

    retcode = SQLSetConnectAttr( dbc, SQL_AUTOCOMMIT,
       (SQLPOINTER)SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER);
  6. Call the ODBC connection function:
    if (retcode == SQL_SUCCESS || retcode ==
       SQL_SUCCESS_WITH_INFO)
    {
       printf( "dbc allocated\n" );
       retcode = SQLConnect( dbc, (SQLCHAR*) "MANGO", 
          SQL_NTS, (SQLCHAR*) "sa", SQL_NTS, 
          (SQLCHAR*) "", SQL_NTS );
       if (retcode == SQL_SUCCESS || retcode ==       SQL_SUCCESS_WITH_INFO)
          {
             // successfully connected.
          }
    }

You can find a complete sample of establishing a connection in your installation directory.

Notes on Usage

  • Every string passed to ODBC has a corresponding length. If the length is unknown, you can pass SQL_NTS indicating that it is a Null Terminated String whose end is marked by the null character (\0).

  • Use the SQLSetConnectAttr function to control details of the connection. For example, this statement turns off ODBC autocommit behavior:

retcode = SQLSetConnectAttr( dbc, SQL_AUTOCOMMIT, 
   (SQLPOINTER)SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER );

Many aspects of the connection can be controlled through the connection parameters.

For more information including a list of connection attributes, see SQLSetConnectAttr in the Microsoft ODBC Programmer's Reference.

Related concepts
Connections to a Database