Initializing CLI applications is part of the larger task of programming
with CLI. The task of initializing CLI applications involves allocating environment and connection
handles and then connecting to the data source.
Procedure
To initialize the application:
- Allocate an environment handle by calling
SQLAllocHandle()
with a HandleType of SQL_HANDLE_ENV and an InputHandle of SQL_NULL_HANDLE. For example:
SQLAllocHandle (SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
Use the allocated environment handle, returned
in the *OutputHandlePtr argument (henv in the example), for all subsequent
calls that require an environment handle.
- Optional: Set environment attributes for your
application by calling
SQLSetEnvAttr()
with the required environment attribute for each attribute
you want set. Important: If you plan to run your
application as an ODBC application, you must set the SQL_ATTR_ODBC_VERSION
environment attribute using SQLSetEnvAttr()
. Setting this attribute for applications that are strictly CLI applications is recommended but not required.
- Allocate a connection handle by calling
SQLAllocHandle()
with a HandleType of SQL_HANDLE_DBC using the environment handle returned from Step 1 as the InputHandle argument. For example:
SQLAllocHandle (SQL_HANDLE_DBC, henv, &hdbc);
Use the allocated connection handle, returned in the *OutputHandlePtr argument (hdbc in the example), for all
subsequent calls that require a connection handle.
- Optional: Set connection attributes for your
application by calling
SQLSetConnectAttr()
with the required connection attribute for each attribute
you want set.
- Connect to a data source by calling one of following functions
with the connection handle you allocated in Step 3 for each data source
you want to connect to:
- SQLConnect(): basic database connection method.
For example:
SQLConnect (hdbc, server, SQL_NTS, user, SQL_NTS, password, SQL_NTS);
where SQL_NTS is a special string length value that indicates the
referenced string is null-terminated.
- SQLDriverConnect(): extended connect function
that allows additional connect options and offers Graphical User Interface
support. For example:
char * connStr = "DSN=SAMPLE;UID=;PWD=;";
SQLDriverConnect (hdbc, (SQLHWND)NULL, connStr, SQL_NTS,
NULL, 0, NULL, SQL_DRIVER_NOPROMPT);
- SQLBrowseConnect(): least common connection
method that iteratively returns the attributes and attribute values
for connecting to a data source. For example:
char * connInStr = "DSN=SAMPLE;UID=;PWD=;";
char outStr[512];
SQLBrowseConnect (hdbc, connInStr, SQL_NTS, outStr,
512, &strLen2Ptr);
Results
Now that your application has been initialized, you can proceed
to processing transactions.