You are on page 1of 9

ADO Data Bases

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>

#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;

SUNSAT The Perfect Team


ADO Data Bases

//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;
}

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)

SUNSAT The Perfect Team


ADO Data Bases

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>

#import "C:\Program Files\Common Files\System\ADO\msado15.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

SUNSAT The Perfect Team


ADO Data Bases

{
//Create the Connection pointer
hr = pConn.CreateInstance((__uuidof(Connection)));
if(FAILED(hr))
{
printf("Error instantiating Connection object\n");
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("%s\n",(LPCSTR)strSQL);

//Execute the insert statement


pConn->Execute(strSQL,NULL,adExecuteNoRecords);

printf("Data Added Successfully\n",(LPCSTR)strSQL);

//Close the database


pConn->Close();

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

cleanup:

SUNSAT The Perfect Team


ADO Data Bases

CoUninitialize();

return 0;
}

C++ ADO Stored Procedure Using Command Object

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.

C++ ADO Stored Procedure Using Command Object - Table:

CREATE TABLE [dbo].[TestTable] (


[Person] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Age] [int] NULL ,
[DateofBirth] [datetime] NULL ,
[Salary] [money] NULL
) ON [PRIMARY]
GO

The above table is used for the ADO C++ Stored Procedure sample.

C++ ADO Stored Procedure Using Command Object - Stored Procedure script:

The script generated in SQL Server for the sample is as follows.

CREATE PROCEDURE [dbo].[spTestTable] ( @strCompanyName char(50), @iAge int,


@dob datetime, @mSalary money) As Insert into
TestTable(Person,Age,DateofBirth,Salary) Values (@strCompanyName, @iAge, @dob,
@mSalary);
GO

C++ ADO Stored Procedure Using Command Object - Writing the code in C++:

The following are the steps to write C++ ADO code.

1. Import the msadoX.dll from the right folder.

SUNSAT The Perfect Team


ADO Data Bases

2. Create the connection string.


3. Open the ADO connection.
4. Create the C++ ADO Command Object and set the type as adCmdStoredProc.
5. Append the parameters to the Command object using CreateParameter and
Append function.
6. Execute the command.
7. Close the connection.

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.

C++ ADO type - Integer:

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));

C++ ADO type - String:

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));

C++ ADO type - Date:

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.

SUNSAT The Perfect Team


ADO Data Bases

COleDateTime vOleDOB( 2004, 2,1 , 0, 0 , 0 ) ;

C++ ADO type - Currency:

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.

C++ ADO Stored Procedure Using Command Object - Sample Program:

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.

#include <afxwin.h> //This program uses MFC


#include <Afxdisp.h>
#include <stdio.h>

#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \


no_namespace rename("EOF", "EndOfFile")

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;

_ConnectionPtr pConn = NULL;


_CommandPtr pCom;
// Define string variables for connection
_bstr_t strCon("Provider=SQLOLEDB.1;Persist Security Info=False;User
ID=username;Password=passwordvalue;Initial Catalog=database;Data
Source=(local);Integrated Security=SSPI;");

SUNSAT The Perfect Team


ADO Data Bases

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 object\n");
goto cleanup;
}

//Open the SQL Server connection


hr = pConn->Open(strCon,"","",0);
if(FAILED(hr))
{
printf("Error Opening Database object\n");
goto cleanup;
}

//Create the C++ ADO Command Object


pCom.CreateInstance(__uuidof(Command));
pCom->ActiveConnection = pConn;

//Make the ADO C++ command object to accept stored procedure


pCom->CommandType = adCmdStoredProc ;

//Tell the name of the Stored Procedure to the command object


pCom->CommandText = _bstr_t("dbo.spTestTable");

//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

SUNSAT The Perfect Team


ADO Data Bases

COleCurrency vOleSalary(5000,55);

//Use COleDateTime class for Date type


COleDateTime vOleDOB( 2004, 2,1 , 0, 0 , 0 ) ;

//Add Parameters to the C++ ADO Command Object


//This adds the string parameter
pCom->Parameters->Append(pCom-
>CreateParameter(_bstr_t("strCompanyName"),adChar,adParamInput,50,vName));
pCom->Parameters->Append(pCom-
>CreateParameter(_bstr_t("iAge"),adInteger,adParamInput,4,vAge));
pCom->Parameters->Append(pCom-
>CreateParameter(_bstr_t("dob"),adDate,adParamInput,8,_variant_t(vOleDOB)));
pCom->Parameters->Append(pCom-
>CreateParameter(_bstr_t("mSalary"),adCurrency,adParamInput,8,_variant_t(vOleSalary
)));

_variant_t vNull;
vNull.vt = VT_ERROR;
vNull.scode = DISP_E_PARAMNOTFOUND;

pCom->Execute(NULL,NULL,adCmdStoredProc);

printf("Data Added Successfully\n");


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

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;
}

SUNSAT The Perfect Team

You might also like