How to connect to a database (odbc) from c++

 ANS 1 : This example C++/MFC program demonstrates connection to any ODBC data source and producing recordsets from SQL SELECT statements and SQL Stored Procedures. Although the majority of the foundations of the program has been generated by the MFC AppWizard, a majority of the Multiple Document Interface has been adapted using Example 28D. The code marked in grey has been included for completeness for the MFC application. Code not marked in this way is directly related to connecting to ODBC databases and recordsets. 

Ans 2 : Before we start there are several things, which we need to ensure. Firstly I was trying to achieve this communication between MS Access 97 and MS Visual C++ 5.0; they were both running under the Windows 98 operating system on a Pentium Pro PC. I was also using MS Personal Web server. Make sure that all of the above mentioned software has been installed and is configured correctly. Now we have to create an ODBC data-source, which points to your MS Access database. Double click the "32bit ODBC" icon in Control Panel to start the ODBC administrator. Next click the "Add" button to create a new data-source, select the driver you wish to use (if your database is an MS Access database select the "Microsoft Access Driver" and so on) and when you have done this click the "finish" button. In the next box you need to enter a name for the data source in the "Data Source Name" field, a description can also be entered in the "Description" field but this is optional. Next you need to click the "Select" button from the "Database" field. A browser box appears where you select the location of your MS Access database file. When done click the "OK" button to return back to the previous screen and "OK" again to complete the creation of the data source. When this has been completed click the "OK" button to quit the ODBC administrator.

Connecting C/C++ to the ODBC data source

We are now ready to produce a C program that will open a connection to the database and perform an SQL query. The SQL query can be any SQL statement so it can be used to search, insert, update or delete data in the database. This program will not do any validation of whether or not a record with the same value already exists in the database table and it will not do any validation on whether the SQL string is a legal SQL statement. The source is given below to connect to the ODBC data source and must be run on the same machine that the ODBC database is running on. A set of C functions are supplied with ODBC and are found in the two header files sql.h and sqlext.h both of which must be included in the program using the "#include" operation.


Connecting to an Ms Access Database via ODBC with C/C++

// This program connects to an ODBC data source called "db97".  It then executes a SQL statement “SELECT Model

// FROM Makes WHERE Make = 'Vauxhall';" which should return all models made by Vauxhall stored in the database
// Author: Mark Lee-Dell      Date: 28/05/99        Name: sqlexecute.cpp

#include <windows.h>

#include <sqlext.h>

#include <stdio.h>


int main(void)


          HENV   hEnv = NULL;                    // Env Handle from SQLAllocEnv()

          HDBC   hDBC = NULL;                             // Connection handle

          HSTMT          hStmt = NULL;                            // Statement handle

          UCHAR szDSN[SQL_MAX_DSN_LENGTH] = "db97"; // Data Source Name buffer
UCHAR*         szUID = NULL;                            // User ID buffer

          UCHAR*         szPasswd = NULL;                                 // Password buffer

          UCHAR szModel[128];                                      // Model buffer

          SDWORD        cbModel;                                    // Model buffer bytes recieved

          UCHAR szSqlStr[] = "Select Model From Makes Where Make='Vauxhall'"; // SQL string

          RETCODE       retcode;                                     // Return code


          // Allocate memory for ODBC Environment handle

          SQLAllocEnv (&hEnv);


          // Allocate memory for the connection handle

          SQLAllocConnect (hEnv, &hDBC);


          // Connect to the data source "db97" using userid and password.

          retcode = SQLConnect (hDBC, szDSN, SQL_NTS, szUID, SQL_NTS, szPasswd, SQL_NTS);


          if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)


           // Allocate memory for the statement handle

           retcode = SQLAllocStmt (hDBC, &hStmt);


           // Prepare the SQL statement by assigning it to the statement handle

           retcode = SQLPrepare (hStmt, szSqlStr, sizeof (szSqlStr));


           // Execute the SQL statement handle

           retcode = SQLExecute (hStmt);


           // Project only column 1 which is the models

           SQLBindCol (hStmt, 1, SQL_C_CHAR, szModel, sizeof(szModel), &cbModel);


           // Get row of data from the result set defined above in the statement

           retcode = SQLFetch (hStmt);


           while (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)


                             printf ("\t%s\n", szModel);     // Print row (model)

Added on May 23, 2007 Comment