C++ ADO Insert Sample

  This following sample code describes how to insert a record into a sample table in SQL Server. The sample code inserts data for each one of the following types.

  • Number
  • Varchar
  • Date
  • Money(currency)        

    The sample first creates a connection string for the SQL Server database. It then instantiates the _ConnectionPtr interface, with a call to the CoCreateInstance. Any call to the CoCreateInstance should be preceded with a CoInitialize or CoInitializeEx at least once during the life time of the program.
The reason behind this call is to initialize the COM libraries. After this call any COM call can be made. After the call to CoCreateInstance, we open the database connection with the connection string.
The _ConnectionPtr object has the capability to execute an SQL DML statement like Insert, Update and Delete. The sample code uses this _ConnectionPtr object’s Execute member function for inserting the record into the table.


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

#import "C:Program FilesCommon FilesSystemADOmsado15.dll"
no_namespace rename("EOF", "EndOfFile")

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

/*The following variables will be initialized with necessary values and  appended to the strSQL values*/
_bstr_t strName;
_bstr_t strAge;
_bstr_t strDOB;
_bstr_t strSalary;

    _ConnectionPtr pConn = NULL;
// Define string variables for ADO connection
_bstr_t strCon("Provider=SQLOLEDB.1;Persist Security Info=False;User     ID=username;Password=password;Initial Catalog=databasename;Data Source=(local);Integrated Security=SSPI;");

HRESULT hr = S_OK;

//Initialize the COM Library
CoInitialize(NULL);

try
{
//Create the Connection pointer
hr = pConn.CreateInstance((__uuidof(Connection)));
if(FAILED(hr))
{
printf("Error instantiating Connection objectn");
goto cleanup;
}

//Open the SQL Server connection
hr = pConn->Open(strCon,"","",0);
if(FAILED(hr))
{
printf("Error Opening Database object using ADO _ConnectionPtr n");
goto cleanup;
}

/*Initialize the values */
strName = "'Codersource C++ ADO insert Sample',";
strAge = "10,";
strDOB = "'02/10/2004',";
strSalary = "1010.10)";

/* Append the values to the Insert Statement */
_bstr_t strSQL("Insert into Table1(Name,Age,DOBirth,Salary) Values(");

strSQL += strName + strAge + strDOB + strSalary ;

printf("%sn",(LPCSTR)strSQL);

//Execute the insert statement
pConn->Execute(strSQL,NULL,adExecuteNoRecords);

printf("Data Added Successfullyn",(LPCSTR)strSQL);

//Close the database
pConn->Close();

}
catch(_com_error & ce)
{
printf("Error:%sn",ce.ErrorInfo);
}

cleanup:
CoUninitialize();

return 0;
}

The following sample is a complete program for inserting one record into a table named “Table1”. Replace the username, password, databasename,(local) with the local username, password, database name and the server name. There is a similar article named C++ ADO Stored Procedure Using Command Object, which explains how to use a stored procedure in C++ ADO.