MDAC 2.5 SDK - ODBC Programmer's Reference
Chapter 21: ODBC API Reference


 

SQLConnect

Conformance

Version Introduced: ODBC 1.0
Standards Compliance: ISO 92

Summary

SQLConnect establishes connections to a driver and a data source. The connection handle references storage of all information about the connection to the data source, including status, transaction state, and error information.

Syntax

SQLRETURN SQLConnect(
     SQLHDBC     ConnectionHandle,
     SQLCHAR *     ServerName,
     SQLSMALLINT     NameLength1,
     SQLCHAR *     UserName,
     SQLSMALLINT     NameLength2,
     SQLCHAR *     Authentication,
     SQLSMALLINT     NameLength3);

Arguments

ConnectionHandle

[Input]
Connection handle.

ServerName

[Input]
Data source name. For information about how an application chooses a data source, see "Choosing a Data Source or Driver" in Chapter 6, "Connecting to a Data Source or Driver."

NameLength1

[Input]
Length of *ServerName.

UserName

[Input]
User identifier.

NameLength2

[Input]
Length of *UserName.

Authentication

[Input]
Authentication string (typically the password).

NameLength3

[Input]
Length of *Authentication.

Returns

SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_ERROR, or SQL_INVALID_HANDLE.

Diagnostics

When SQLConnect returns SQL_ERROR or SQL_SUCCESS_WITH_INFO, an associated SQLSTATE value can be obtained by calling SQLGetDiagRec with a HandleType of SQL_HANDLE_DBC and a Handle of ConnectionHandle. The following table lists the SQLSTATE values commonly returned by SQLConnect and explains each one in the context of this function; the notation "(DM)" precedes the descriptions of SQLSTATEs returned by the Driver Manager. The return code associated with each SQLSTATE value is SQL_ERROR, unless noted otherwise.

SQLSTATE Error Description
01000 General warning Driver-specific informational message. (Function returns SQL_SUCCESS_WITH_INFO.)
01S02 Option value changed The driver did not support the specified value of the ValuePtr argument in SQLSetConnectAttr and substituted a similar value. (Function returns SQL_SUCCESS_WITH_INFO.)
08001 Client unable to establish connection The driver was unable to establish a connection with the data source.
08002 Connection name in use (DM) The specified ConnectionHandle had already been used to establish a connection with a data source, and the connection was still open or the user was browsing for a connection.
08004 Server rejected the connection The data source rejected the establishment of the connection for implementation-defined reasons.
08S01 Communication link failure The communication link between the driver and the data source to which the driver was attempting to connect failed before the function completed processing.
28000 Invalid authorization specification The value specified for the argument UserName or the value specified for the argument Authentication violated restrictions defined by the data source.
HY000 General error An error occurred for which there was no specific SQLSTATE and for which no implementation-specific SQLSTATE was defined. The error message returned by SQLGetDiagRec in the *MessageText buffer describes the error and its cause.
HY001 Memory allocation
error
(DM) The Driver Manager was unable to allocate memory required to support execution or completion of the function.

The driver was unable to allocate memory required to support execution or completion of the function.

HY013 Memory management error The function call could not be processed because the underlying memory objects could not be accessed, possibly because of low memory conditions.
HY090 Invalid string or buffer length (DM) The value specified for argument NameLength1, NameLength2, or NameLength3 was less than 0 but not equal to SQL_NTS.

(DM) The value specified for argument NameLength1 exceeded the maximum length for a data source name.

HYT00 Timeout expired The query timeout period expired before the connection to the data source completed. The timeout period is set through SQLSetConnectAttr, SQL_ATTR_LOGIN_TIMEOUT.
HYT01 Connection timeout expired The connection timeout period expired before the data source responded to the request. The connection timeout period is set through SQLSetConnectAttr, SQL_ATTR_CONNECTION_TIMEOUT.
IM001 Driver does not support this function (DM) The driver specified by the data source name does not support the function.
IM002 Data source not found and no default driver specified (DM) The data source name specified in the argument ServerName was not found in the system information, nor was there a default driver specification.
IM003 Specified driver could not be connected to (DM) The driver listed in the data source specification in system information was not found or could not be connected to for some other reason.
IM004 Driver's SQLAllocHandle on SQL_HANDLE_ENV failed (DM) During SQLConnect, the Driver Manager called the driver's SQLAllocHandle function with a HandleType of SQL_HANDLE_ENV and the driver returned an error.
IM005 Driver's SQLAllocHandle on SQL_HANDLE_DBC failed (DM) During SQLConnect, the Driver Manager called the driver's SQLAllocHandle function with a HandleType of SQL_HANDLE_DBC and the driver returned an error.
IM006 Driver's SQLSetConnectAttr failed During SQLConnect, the Driver Manager called the driver's SQLSetConnectAttr function and the driver returned an error. (Function returns SQL_SUCCESS_WITH_INFO.)
IM009 Unable to connect to translation DLL The driver was unable to connect to the translation DLL that was specified for the data source.
IM010 Data source name too long (DM) *ServerName was longer than SQL_MAX_DSN_LENGTH characters.

Comments

For information about why an application uses SQLConnect, see "Connecting with SQLConnect" in Chapter 6, "Connecting to a Data Source or Driver."

The Driver Manager does not connect to a driver until the application calls a function (SQLConnect, SQLDriverConnect, or SQLBrowseConnect) to connect to the driver. Until that point, the Driver Manager works with its own handles and manages connection information. When the application calls a connection function, the Driver Manager checks whether a driver is currently connected to for the specified ConnectionHandle:

The driver then allocates handles and initializes itself.

When the application calls SQLDisconnect, the Driver Manager calls SQLDisconnect in the driver. However, it does not disconnect the driver. This keeps the driver in memory for applications that repeatedly connect to and disconnect from a data source. When the application calls SQLFreeHandle with a HandleType of SQL_HANDLE_DBC, the Driver Manager calls SQLFreeHandle with a HandleType of SQL_HANDLE_DBC and then SQLFreeHandle with a HandleType of SQL_HANDLE_ENV in the driver, and then disconnects the driver.

An ODBC application can establish more than one connection.

Driver Manager Guidelines

The contents of *ServerName affect how the Driver Manager and a driver work together to establish a connection to a data source.

After being connected to by the Driver Manager, a driver can locate its corresponding data source specification in the system information and use driver-specific information from the specification to complete its set of required connection information.

If a default translation library is specified in the system information for the data source, the driver connects to it. A different translation library can be connected to by calling SQLSetConnectAttr with the SQL_ATTR_TRANSLATE_LIB attribute. A translation option can be specified by calling SQLSetConnectAttr with the SQL_ATTR_TRANSLATE_OPTION attribute.

If a driver supports SQLConnect, the driver keyword section of the system information for the driver must contain the ConnectFunctions keyword with the first character set to "Y."

Connection Pooling

Connection pooling allows an application to reuse a connection that has already been created. When connection pooling is enabled and SQLConnect is called, the Driver Manager attempts to make the connection using a connection that is part of a pool of connections in an environment that has been designated for connection pooling. This environment is a shared environment that is used by all applications that use the connections in the pool.

Connection pooling is enabled before the environment is allocated by calling SQLSetEnvAttr to set SQL_ATTR_CONNECTION_POOLING to SQL_CP_ONE_PER_DRIVER (which specifies a maximum of one pool per driver) or SQL_CP_ONE_PER_HENV (which specifies a maximum of one pool per environment). SQLSetEnvAttr in this case is called with EnvironmentHandle set to null, which makes the attribute a process-level attribute. If SQL_ATTR_CONNECTION_POOLING is set to SQL_CP_OFF, connection pooling is disabled.

Once connection pooling has been enabled, SQLAllocHandle with a HandleType of SQL_HANDLE_ENV is called to allocate an environment. The environment allocated by this call is a shared environment because connection pooling has been enabled. The environment to be used is not determined, however, until SQLAllocHandle with a HandleType of SQL_HANDLE_DBC is called.

SQLAllocHandle with a HandleType of SQL_HANDLE_DBC is called to allocate a connection. The Driver Manager attempts to find an existing shared environment that matches the environment attributes set by the application. If no such environment exists, one is created as an implicit shared environment. If a matching shared environment is found, the environment handle is returned to the application and its reference count is incremented.

The connection to be used is not determined, however, until SQLConnect is called. At that point, the Driver Manager attempts to find an existing connection in the connection pool that matches the criteria requested by the application. This criteria includes the connection options requested in the call to SQLConnect (the values of the ServerName, UserName, and Authentication keywords) and any connection attributes set since SQLAllocHandle with a HandleType of SQL_HANDLE_DBC was called. The Driver Manager checks this criteria against the corresponding connection keywords and attributes in connections in the pool. If a match is found, the connection in the pool is used. If no match is found, a new connection is created.

If the SQL_ATTR_CP_MATCH environment attribute is set to SQL_CP_STRICT_MATCH, the match must be exact for a connection in the pool to be used. If the SQL_ATTR_CP_MATCH environment attribute is set to SQL_CP_RELAXED_MATCH, the connection options in the call to SQLConnect must match but not all of the connection attributes must match.

The following rules are applied when a connection attribute, as set by the application before SQLConnect is called, does not match the connection attribute of the connection in the pool:

When the application calls SQLDisconnect to disconnect, the connection is returned to the connection pool and is available for reuse.

Optimizing Connection Pooling Performance

When distributed transactions are involved, it is possible to optimize connection pooling performance by using SQL_DTC_TRANSITION_COST, which is a SQLUINTEGER bitmask. The transitions referred to are the transitions of the connection attribute SQL_ATTR_ENLIST_IN_DTC going from value 0 to nonzero, and vice versa. This is a connection going from not enlisted in a distributed transaction to enlisted in a distributed transaction, and vice versa. Depending on how the driver has implemented enlistment (setting connection attribute SQL_ATTR_ENLIST_IN_DTC), these transitions may be expensive and should therefore be avoided for best performance.

The value returned by the driver contains any combination of the following bits:

There is a performance vs. connection usage tradeoff. If a driver indicates that one or more of these transitions are expensive, the driver manager's connection pooler responds to this by keeping more connections in the pool. Some of the connections in the pool are preferred for nontransactional use, and some are preferred for transactional use. However, if the driver indicates that these transitions are not expensive, fewer connections can be used, perhaps alternating between nontransactional and transactional use.

Drivers that do not support SQL_ATTR_ENLIST_IN_DTC do not need to support SQL_DTC_TRANSITION_COST. For drivers that support SQL_ATTR_ENLIST_IN_DTC but not SQL_DTC_TRANSITION_COST, it is assumed that the transitions are not expensive, as though the driver returned 0 (no bits set) for this value.

Although SQL_DTC_TRANSITION_COST was introduced in ODBC 3.5, an ODBC 2.x driver can also support it because the driver manager will query this information regardless of the driver version.

Code Example

In the following example, an application allocates environment and connection handles. It then connects to the SalesOrders data source with the user ID JohnS and the password Sesame and processes data. When it has finished processing data, it disconnects from the data source and frees the handles.

SQLHENV     henv;
SQLHDBC     hdbc;
SQLHSTMT    hstmt;
SQLRETURN   retcode;

      /*Allocate environment handle */
retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
   /* Set the ODBC version environment attribute */
   retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 

   if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
      /* Allocate connection handle */
      retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); 

      if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
         /* Set login timeout to 5 seconds. */
         SQLSetConnectAttr(hdbc, (void*)SQL_LOGIN_TIMEOUT, 5, 0);

         /* Connect to data source */
         retcode = SQLConnect(hdbc, (SQLCHAR*) "Sales", SQL_NTS,
                  (SQLCHAR*) "JohnS", SQL_NTS,
                  (SQLCHAR*) "Sesame", SQL_NTS);

         if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO){
            /* Allocate statement handle */
            retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); 

            if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
            /* Process data */
                  ;
                  ;
                  ;

               SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
            }
            SQLDisconnect(hdbc);
         }
         SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
      }
   }
   SQLFreeHandle(SQL_HANDLE_ENV, henv);

Related Functions

For information about See
Allocating a handle SQLAllocHandle
Discovering and enumerating values required to connect to a data source SQLBrowseConnect
Disconnecting from a data source SQLDisconnect
Connecting to a data source using a connection string or dialog box SQLDriverConnect
Returning the setting of a connection attribute SQLGetConnectAttr
Setting a connection attribute SQLSetConnectAttr