Click here to Skip to main content
15,888,301 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Dear All,
Can anybody know
Is it possible to connect SQL Server with C++ Program.
If yes
I need to execute one simple Query through the front end C++ program
Thank you,
Posted

You can use below code for connecting to SQL server using ODBC.

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>

using namespace std;

void show_error(unsigned int handletype, const SQLHANDLE& handle)
{
	SQLCHAR sqlstate[1024];
	SQLCHAR message[1024];
	if(SQL_SUCCESS == SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, message, 1024, NULL))
	cout<<"Message: "<<message<<"\nSQLSTATE: "<<sqlstate<<endl;
}

int main()
{
	SQLHANDLE sqlenvhandle;    
	SQLHANDLE sqlconnectionhandle;
	SQLHANDLE sqlstatementhandle;
	SQLRETURN retcode;

	do
	{
		if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle))
			break;

		if(SQL_SUCCESS!=SQLSetEnvAttr(sqlenvhandle,SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0)) 
			break;

		if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle))
			break;

		SQLCHAR retconstring[1024];
		switch(SQLDriverConnect (sqlconnectionhandle, NULL, 
				(SQLCHAR*)"DRIVER={SQL Server};SERVER=localhost, 1433;DATABASE=MyDatabase;UID=sa;PWD=Admin-123;", 
				SQL_NTS, retconstring, 1024, NULL,SQL_DRIVER_NOPROMPT))
		{
			case SQL_SUCCESS_WITH_INFO:
				show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
				break;
			case SQL_INVALID_HANDLE:
			case SQL_ERROR:
				show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
				retcode = -1;
				break;
			default:
				break;
		}

		if(retcode == -1)
			break;

		if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle))
			break;

		if(SQL_SUCCESS!=SQLExecDirect(sqlstatementhandle, (SQLCHAR*)"select * from testtable", SQL_NTS))
		{
			show_error(SQL_HANDLE_STMT, sqlstatementhandle);
			break;
		}
		else
		{
			char name[64];
			char address[64];
			int id;
			while(SQLFetch(sqlstatementhandle)==SQL_SUCCESS)
			{
				SQLGetData(sqlstatementhandle, 1, SQL_C_ULONG, &id, 0, NULL);
				SQLGetData(sqlstatementhandle, 2, SQL_C_CHAR, name, 64, NULL);
				SQLGetData(sqlstatementhandle, 3, SQL_C_CHAR, address, 64, NULL);
				cout<<id<<" "<<name<<" "<<address<<endl;
			}
		}
	}
	while(FALSE);
	SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle );
	SQLDisconnect(sqlconnectionhandle);
	SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
	SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);

}
 
Share this answer
 
v2
The C++ ADO select query sample below is self explanatory. If you want to execute the code, copy and paste the code in a Win32 or console application, Edit the Connection String & SQL Statement, and then compile the program.

#include <windows.h>
#include <stdio.h>

#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")

int main(int argc, char* argv[])
{

HRESULT hr = S_OK;
    try
    {
         CoInitialize(NULL);
          // Define string variables.
        _bstr_t strCnn("Provider=SQLOLEDB.1;Persist Security Info=False;User       ID=username;Password=passwd;Initial Catalog=database;Data Source=(local);Integrated Security=SSPI;");

       _RecordsetPtr pRstAuthors = NULL;

      // Call Create instance to instantiate the Record set
      hr = pRstAuthors.CreateInstance(__uuidof(Recordset));

      if(FAILED(hr))
      {
            printf("Failed creating record set instance\n");
            return 0;
       }

      //Open the Record set for getting records from Author table
      pRstAuthors->Open("SELECT Author_ID,username FROM Author",strCnn, adOpenStatic,     adLockReadOnly,adCmdText);

      //Declare a variable of type _bstr_t
     _bstr_t valField1;
     int valField2;

     pRstAuthors->MoveFirst();

    //Loop through the Record set
    if (!pRstAuthors->EndOfFile)
    {
       while(!pRstAuthors->EndOfFile)
       {
          valField1 = pRstAuthors->Fields->GetItem("username")->Value;
          valField2 = pRstAuthors->Fields->GetItem("Author_ID")->Value.intVal;
          printf("%d - %s\n",valField2,(LPCSTR)valField1);
          pRstAuthors->MoveNext();
       }
    }

   }
   catch(_com_error & ce)
   {
      printf("Error:%s\n",ce.Description);
   }

  CoUninitialize();
  return 0;
}


http://www.codersource.net/C/CDatabase/CADOSelectSample.aspx[^]
 
Share this answer
 
v2
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <sqltypes.h>
  //#include <sql.h>
#include "sqlext.h"
using namespace std;

void show_error(unsigned int handletype, const SQLHANDLE& handle)
{
     SQLWCHAR sqlstate[1024];
     SQLWCHAR message[1024];
     if(SQL_SUCCESS == SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, message, 1024, NULL))
         cout<<"Message: "<<message<<"\nSQLSTATE: "<<sqlstate<<endl;
 }
int _tmain(int argc, _TCHAR* argv[])
{
	SQLHANDLE sqlenvhandle;    
    SQLHANDLE sqlconnectionhandle;
    SQLHANDLE sqlstatementhandle;
    SQLRETURN retcode;
	if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle))
		goto FINISHED;
	if(SQL_SUCCESS!=SQLSetEnvAttr(sqlenvhandle,SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0)) 
		goto FINISHED;
	if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle))
		goto FINISHED;

	SQLWCHAR retconstring[1024];
	switch(SQLDriverConnect (sqlconnectionhandle, 
                 NULL, 
                 (SQLWCHAR*)"DSN=test;UID=sa;PWD=123;", 
                 SQL_NTS, 
                 retconstring, 
                 1024, 
                 NULL,
                 SQL_DRIVER_NOPROMPT))
	{
         case SQL_SUCCESS_WITH_INFO:
             show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
             break;
         case SQL_INVALID_HANDLE:
         case SQL_ERROR:
             show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
             goto FINISHED;
         default:
             break;
     }
     
     if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle))
         goto FINISHED;
 
     if(SQL_SUCCESS!=SQLExecDirect(sqlstatementhandle, (SQLWCHAR*)"select * from testtable", SQL_NTS))
	 {
         show_error(SQL_HANDLE_STMT, sqlstatementhandle);
         goto FINISHED;
     }
     else
	 {
         char name[64];
         char address[64];
         int id;
         while(SQLFetch(sqlstatementhandle)==SQL_SUCCESS){
             SQLGetData(sqlstatementhandle, 1, SQL_C_ULONG, &id, 0, NULL);
             SQLGetData(sqlstatementhandle, 2, SQL_C_CHAR, name, 64, NULL);
             SQLGetData(sqlstatementhandle, 3, SQL_C_CHAR, address, 64, NULL);
             cout<<id<<" "<<name<<" "<<address<<endl;
         }
     }
 
 FINISHED:
     SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle );
     SQLDisconnect(sqlconnectionhandle);
     SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
     SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);

 
	return 0;
}
 
Share this answer
 
v2
Comments
Chandrasekharan P 7-Mar-12 0:08am    
When you put some code then use the pre tags. it becomes easier for others to read.
Member 11513987 10-Mar-15 14:38pm    
Chandrasekharan, If I use the code above at build I get a warning that retcode is unreferenced and 2 errors for sqlconionhandle and sqlstatementhandel as uninitialized pointers. I'm using Visual Studio 2013 and my project is a windows console project. Can you tell me what I am doing wrong?
kjhiuhg 5-Jan-17 10:43am    
Casting the constants with '(SQLWCHAR*)' won't work. You have to either use the 'L' macro or create wchar constants some other way.
theMadCoder 30-Jan-17 15:01pm    
gotos? really
Google it man
Have a look,here[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900