SQLConnect()--Connect Using a Data Source Name
SQLConnect() allows you to connect to the database using connection attributes stored in the ODBC Data Source Name (DSN) definition. For information about creating an ODBC DSN definition, see
Configure a Data Source (Windows) and
Configure a Data Source (Linux).
The following program is the minimum code required for:
• Initializing ODBC driver
• Setting the ODBC version to version 3
• Connecting to the database
• Disconnecting from the database
• Cleaning up and exiting
Example: SQLConnect() Function
# ifdef _WIN32
# include <windows.h>
# else
# include <stdio.h>
# include <stdlib.h>
# endif
# include <sql.h>
# include <sqlext.h>
main( )
{
HENV henv = NULL;
HDBC hdbc = NULL;
/* Initialize the ODBC environment handle. */
SQLAllocHandle( SQL_HANDLE_ENV, NULL, &henv );
/* Set the ODBC version to version 3 (the highest version) */
SQLSetEnvAttr( henv, SQL_ATTR_ODBC_VERSION,
(void *)SQL_OV_ODBC3, 0 );
/* Allocate the connection handle. */
SQLAllocHandle( SQL_HANDLE_DBC, henv, &hdbc );
/* Connect to the database using the ODBC DSN definition. */
SQLConnect( hdbc, /* Connection handle */
(SQLCHAR *)"myDSN", /* The ODBC DSN definition */
SQL_NTS, /* This is a null-terminated string */
(SQLCHAR *)NULL, /* No username required */
SQL_NTS, /* This is a null-terminated string */
(SQLCHAR *)NULL, /* No password required */
SQL_NTS ); /* This is a null-terminated string */
/* Disconnect from the database. */
SQLDisconnect( hdbc );
/* Free the connection handle. */
SQLFreeHandle( SQL_HANDLE_DBC, hdbc );
/* Free the environment handle. */
SQLFreeHandle( SQL_HANDLE_ENV, henv );
/* Exit this program. */
return( 0 );
}
If your login name is a valid Actian X user for a local database, the above code is all you need to connect through SQLConnect(). See the ODBC User Authorization section for a discussion on authorizing yourself as another user.
Other details of the connection, such as the database name and type of database, are pre-defined in the ODBC DSN definition referenced by the string “myDSN”.
Note that SQLAllocHandle() was invoked to initialize the environment handle and that SQLSetEnvAttr() sets the ODBC version to SQL_OV_ODBC3. These two calls are necessary to initialize your ODBC application as an ODBC level 3 driver. The default is ODBC level 2. We recommend initializing as version 3 because some ODBC level 3 functions, such as the treatment of date and time values, depend on the ODBC version being set at level 3.
Last modified date: 08/14/2024