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

SAP Sybase SQL Anywhere 16.0 » SQL Anywhere Server - Programming » ODBC support » ODBC connection functions

 

Establishing an ODBC connection

Establish an ODBC connection in your application to perform any database operations.

Prérequis

There are no prerequisites for this task.

Contexte et remarques

You can find a complete sample in %SQLANYSAMP16%\SQLAnywhere\ODBCConnect\odbcconnect.cpp.

 Task
  1. Allocate an ODBC environment.

    For example:

    SQLRETURN rc;
    SQLHENV   env;
    rc = 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:

    rc = SQLSetEnvAttr( env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0 );
  3. Allocate an ODBC connection item.

    For example:

    rc = SQLAllocHandle( SQL_HANDLE_DBC, env, &dbc );
  4. 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:

    rc = SQLSetConnectAttr( dbc, SQL_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_OFF, 0 );

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

  5. 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.

  6. Call the ODBC connection function.

    For example:



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

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

Résultat

The application, when built and run, establishes an ODBC connection.

 See also

How to set connection attributes
How to get connection attributes
Threads and connections in ODBC applications