Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 11.0.1 » SQL Anywhere Server - Programming » SQL Anywhere Data Access APIs » SQL Anywhere ODBC API » Choosing an ODBC connection function


Establishing a connection

Your application must establish a connection before it can perform any database operations.

To establish an ODBC connection
  1. Allocate an ODBC environment.

    For example:

    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,
  3. If necessary, assemble the data source or connection string.

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

  4. Allocate an ODBC connection item.

    For example:

    retcode = SQLAllocHandle( SQL_HANDLE_DBC, env, &dbc );
  5. Set any connection attributes that must be set before connecting.

    Some connection attributes must be set before establishing a connection or after establishing a connection, while others can be set either before or after. The SQL_AUTOCOMMIT attribute is one that can be set before or after:

    retcode = SQLSetConnectAttr( dbc,

    For more information, see Setting connection attributes.

  6. Call the ODBC connection function.

    For example:

    if (retcode == SQL_SUCCESS 
        || retcode == SQL_SUCCESS_WITH_INFO) {
       printf( "dbc allocated\n" );
       retcode = SQLConnect( dbc,
          (SQLCHAR*) "SQL Anywhere 11 Demo", SQL_NTS,
          (SQLCHAR* ) "DBA", SQL_NTS,
          (SQLCHAR*) "sql", SQL_NTS );
       if (retcode == SQL_SUCCESS
             || retcode == SQL_SUCCESS_WITH_INFO){
       // successfully connected.

You can find a complete sample in samples-dir\SQLAnywhere\ODBCConnect\odbcconnect.cpp.

  • SQL_NTS   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).

  • SQLSetConnectAttr   By default, ODBC operates in autocommit mode. This mode is turned off by setting SQL_AUTOCOMMIT to false.

    For more information, see Setting connection attributes.

Setting connection attributes
Getting connection attributes
Threads and connections in ODBC applications