Hi All,

The number of  database applications done by using Visual C++ is very less compared to other languages like VB, C#, ASP, Java etc. (Hope you agree with me 😉 ).

Here I’m explaining steps for doing a database application using Visual C++/My SQL /ODBC.

ODBC is a call-level interface that allows applications to access data in any database for which there is an ODBC driver. Using ODBC, you can create database applications with access to any database for which your end user has an ODBC driver. ODBC provides an API that allows your application to be independent of the source database management system (DBMS).(C)MSDN

Step 1. You must include <sqlext.h> and link to ODBC32.LIB When creating an application that uses the ODBC C API.

Step 2. Establish a connection using a connection string that contains the data source name, user IDs, passwords, and other information required by the data source.

a sample connection string is look like this

DRIVER=MySQL ODBC 5.1 Driver;SERVER=”localhost”;PORT=3306;DATABASE=”MyDataBase”;UID=”DBUser”;PWD=”DBUserPwd”;

Step 3. Allocate the different ODBC handles and set different attributes

    • Allocate the ODBC environment by SQL_HANDLE_ENV using the method SQLAllocHandle()
    • Set the ODBC version environment attribute using SQLSetEnvAttr()
      • for eg: SQLSetEnvAttr( m_hSqlEnv, SQL_ATTR_ODBC_VERSION, (void*) SQL_OV_ODBC3, 0 );
    • Allocate the connection handle by SQL_HANDLE_DBC using the method SQLAllocHandle()

Step 4. Connect to the data source by using the connection string and method SQLDriverConnect()

Now you established a connection with the database. 🙂

Now, we are trying to retrieve the data.

Step 5. Allocate the ODBC statement handles by SQL_HANDLE_STMT

Step 6. Execute the prepared statement using SQLExecDirect()

for eg: SQLExecDirect(m_hSqlStmt, (SQLTCHAR*)szQuery, SQL_NTS)

  • Some Tips :
    • You can get the number of COLUMNS in the result set using the method SQLNumResultCols()
    • also the number of ROWS by using SQLRowCount()

Step 7.  Fetch the data result set using SQLFetch()

Step 8. Read the data using SQLGetData();

    • for eg: SQLGetData(m_hSqlStmt, 1, SQL_C_TCHAR, m_szName, 255, &cbName);

Step 9. Close the Connection using SQLDisconnect() and then free the different allocated handles usingSQLFreeHandle().

For vctipsplusplus,

BijU..

To acquire knowledge, one must study; but to acquire wisdom, one must observe