Using ADO from C++

Microsoft ActiveX Data Object (ADO) provides an easy way to data access and manipulation that is independent of data stores, tools, and languages. This flexibility and easy-to-code facility makes ADO the perfect choice for developers. ADO is implemented with Component Object Model (COM) interfaces. Unlike VB programmers, C++ programmers must know the details of using COM for using ADO. So, using ADO from C++ is still very complex. But, it is possible to get an easy ADO programming model from C++, which can help to hide the details of using COM. In this article, I demonstrate a C++ class to do this that encapsulates the ADO connection object. You can apply same technique for encapsulating other ADO objects.

Adding ADO Support to a C++ Program

One way to add ADO support to your C++ program is to import ADO type library information. The type library for the current ADO is contained within the ADO DLL, msado15.dll. You can import this type library by importing msado15.dll by using the #import directive:

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

Of course, you may need to change the path of msado15.dll according to the location where the file is found on your machine. Because I don't mention the no_namespace option, the directive generates a type library header (generally msado15.tlh) that contains typedef declarations, smart pointers for interfaces, and enumerators under the ADODB namespace. The rename macro tells the preprocessor to replace the EOF constants by EndOfFile. ADO defines nine objects (Connection, Command, Recordset, Record, Stream, Parameter, Field, Property, and Error) and four collections (Parameters, Fields, Properties, and Errors). The #import directive generates smart pointer-type declarations for all the ADO objects. For example, a variable that points to a _Connection object is of the _ConnectionPtr type. So, if you want to refer to the _Connection object, you have to declare a variable of the _ConnectionPtr type.

ADODB::_ConnectionPtr Cnn;

Now, create a C/C++ header file named .Database.h. and add the codes given below:

#import "c:\Program Files\Common Files\System\ADO\msado15.dll"
        rename("EOF", "EndOfFile")
typedef ADODB::_RecordsetPtr  RecPtr;
typedef ADODB::_ConnectionPtr CnnPtr;

Notice that all typedef declarations, smart pointers for interfaces, and enumerators are in msado15.tlh. The compiler automatically generates this file after compiling the above #import directive. You don't need to include this file because C++ is responsible for this file. Now, we are ready to declare a class, which encapsulates the ADO Connection object. Let's write the code for the class that encapsulates the ADO Connection object.


class Database
{
public:
   CnnPtr m_Cnn;
   Database();
   ~ Database();
   bool Open(char* UserName, char* Pwd, char* CnnStr, char* ErrStr);
   RecPtr Execute(char* CmdStr);
   bool Close();
};

Actually, the ADO Connection object has many methods. But, to simplify the code, I declare only three methods (Open, Close, and Execute) to give access to three methods of the connection object: Open establishes a physical connection to a data source, Execute executes a command or stored procedure on the established connection, and Close breaks the established connection.

Using ADO from C++

Now, let's implement the member functions of Database class one by one.

Database::Database()
{
   m_Cnn=NULL;
}

Here, I set m_Cnn to NULL because at this point there is no established connection.

bool Database::Open(char* UserName, char* Pwd, char* CnnStr)
{

   HRESULT hr;
   try
   {
      if(m_Cnn==NULL)
         return 0;
      hr    = m_Cnn.CreateInstance(
         __uuidof( ADODB::Connection ) );
      m_Cnn->Open(CnnStr, UserName, Pwd, NULL);
   }
   catch(_com_error &e)
   {
      //   Handle errors
      return 0;
   }
   return 1;
}

Here, __uuidof( ADODB::Connection ) returns the interface id that is used to create an instance of a Connection object. If a connection object is created successfully, the Open() method tries to establish a physical connection to the data source. Open() takes three parameters: connection string, user name, and password. If a physical connection is established, this function returns 1. I used a catch handler to catch the exception thrown by the methods of Connection object.

RecPtr Database::Execute(char* CmdStr)
{
   try
   {
      if(m_Cnn==NULL)
         return NULL;
      return m_Cnn->Execute(CmdStr,NULL,1);
   }
   catch(_com_error &e)
   {
      //   Handle errors
      return NULL;
   }
}

The Execute() method takes a valid SQL query and returns a smart pointer to the Recordset object.

bool Database::Close()
{
   //is there any established connection?
   //if no, return 0
   if (m_Con==NULL)
      return 0;
   //if any, close that connection
   try
   {
      m_Con->Close();
      m_Con=NULL;
   }
   catch(_com_error &e)
   {
      //   Handle errors
      return 0;
   }
   return hr==S_OK;
}


Database::~Database()
{
   try
   {
   //close connection, if not yet closed
      if (m_Con)
      {
         m_Con->Close();
         m_Con=NULL;
      }
   }
   catch(_com_error &e)
   {
      //   Handle errors
   }
}

Notice that you must initialize COM before using this class. You can do this by adding the following code before using this class.

   if(FAILED(::CoInitialize(NULL)))
      return;

It is good programming practice if you uninitialize COM. You can do this by using ::CoUninitialize() at the end of program.

In this article, I have tried to demonstrate a C++ class by which a C++ programmer can enjoy a VB-like ADO programming model. Download and then review the source code attached with this article; you will see how this technique simplyfies working with ADO. For further information, you can mail me. I will try my best to help you.



About the Author

Prasun Paul

computer science & engineering, CUET

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • In support of their business continuity and disaster recovery plans, many midsized companies endeavor to avoid putting all their eggs in one basket. Understanding the critical role of last-mile connectivity and always available Internet access for their enterprises, savvy firms utilize redundant connections from multiple service providers. Despite the good intentions, their Internet connectivity risk may still be in a single basket. That is because internet service providers (ISPs) and competitive local …

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds