Professional Documents
Culture Documents
ADO Datebases
ADO is the norm of the day for database programming. It has a set of COM classes with
the capability to support all kinds of database operations. This following sample code
describes how to retrieve a set of records from a table.
The sample first creates a connection string for the SQL Server database. It then
instantiates the Record set 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. We call our ADO COM interfaces for opening the Record set object
first with our select query.
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 and compile the
program.
#include <windows.h>
#include <stdio.h>
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;");
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);
pRstAuthors->MoveFirst();
}
catch(_com_error & ce)
{
printf("Error:%s\n",ce.Description);
}
CoUninitialize();
return 0;
}
ADO Insert
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.
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.
#include <windows.h>
#include <stdio.h>
/*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;
HRESULT hr = S_OK;
try
{
//Create the Connection pointer
hr = pConn.CreateInstance((__uuidof(Connection)));
if(FAILED(hr))
{
printf("Error instantiating Connection object\n");
goto cleanup;
}
printf("%s\n",(LPCSTR)strSQL);
}
catch(_com_error & ce)
{
printf("Error:%s\n",ce.ErrorInfo);
}
cleanup:
CoUninitialize();
return 0;
}
Stored Procedures are the fastest way of manipulating data inside a database. Using
stored procedures in ADO requires a little bit of extra code than a normal SQL execution.
It requires the ADO Command object. This Command object can accept any valid
parameter types and execute the stored procedures by applying their parameters.
This article deals with how to insert data into a table using a stored procedure. The data
types integer, char, date and currency are dealt in here. For the purpose of the sample, the
SQL Server database is used. A table has been created with the name TestTable. The
stored procedure created is named as spTestTable and its functionality is to insert data
into table.
The above table is used for the ADO C++ Stored Procedure sample.
C++ ADO Stored Procedure Using Command Object - Stored Procedure script:
C++ ADO Stored Procedure Using Command Object - Writing the code in C++:
C++ ADO Stored Procedure Using Command Object - Handling different types of
Parameters:
Usually handling the parameters will create some issues of syntax and runtime errors.
The following set of code snippets explain how to append parameters of different type to
the command object.
A variant should be used to initialize the parameters. Assign VT_I2 to indicate this is an
integer parameter and add the parameter by calling Append and CreateParameter for
ADO Command object.
VARIANT vIntegerType;
vIntegerType.vt = VT_I2; //Variant type for Integer
vIntegerType.intVal = 10;
pCom->Parameters->Append(pCom-
>CreateParameter(_bstr_t("IntegerParameter"),adInteger,adParamInput,4,vIntegerType));
As usual, a variant should be initialized with VT_BSTR and should be added to the
command object using CreateParameter and Append methods.
VARIANT vName;
vName.vt = VT_BSTR; //Variant type for BSTR
vName.bstrVal = _bstr_t("CoderSource C++ ADO Stored Procedure Sample for String");
pCom->Parameters->Append(pCom-
>CreateParameter(_bstr_t("strCompanyName"),adChar,adParamInput,50,vName));
It is easier to use the OLE class COleDateTime for date type of variables. So the
following variable definition initializes this type. The header file Afxdisp.h should be
used for this class.
It is easier to use the OLE class COleCurrency for currency type of variables. So the
following variable definition initializes this type.The header file Afxdisp.h should be used
for this class.
COleCurrency vOleSalary(5000,55);
It is also possible to use the VARIANT types for date and currency types. But it is much
easier if we use COleCurrency and COleDateTime because these classes support
formatting and string extractions.
The following sample shows how to use the spTestTable stored procedure to insert data
into a table. The sample scripts for the TestTable and spTestTable have to be run in the
SQL Server first. This will create the required table and stored procedure.
After creating the table and stored procedure, the following sample can be used to insert
data into the table.
int main()
{
/*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;
HRESULT hr = S_OK;
try
{
//Create the Connection pointer
hr = pConn.CreateInstance((__uuidof(Connection)));
if(FAILED(hr))
{
printf("Error instantiating Connection object\n");
goto cleanup;
}
//Prepare the Name VARIANT for ADO C++ Command Object Parameter
VARIANT vName;
vName.vt = VT_BSTR; //Variant type for BSTR
vName.bstrVal = _bstr_t("CoderSource C++ ADO Stored Procedure Sample");
//Prepare the Age VARIANT for ADO C++ Command Object Parameter
VARIANT vAge;
vAge.vt = VT_I2; //Variant type for Integer
vAge.intVal = 10;
//Prepare the Salary VARIANT for ADO C++ Command Object Parameter
COleCurrency vOleSalary(5000,55);
_variant_t vNull;
vNull.vt = VT_ERROR;
vNull.scode = DISP_E_PARAMNOTFOUND;
pCom->Execute(NULL,NULL,adCmdStoredProc);
catch(_com_error & e)
{
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
printf("\n Source : %s \n Description : %s
\n",(LPCSTR)bstrSource,(LPCSTR)bstrDescription);
}
cleanup:
CoUninitialize();
return 0;
}