|
|||||||||||||||||||||
|
|||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionMicrosoft ActiveX Data Objects (ADO) allow you to manipulate and store your data in a database server through an OLEDB provider, and as it provides dual interface you are able to use it from both scripting languages such as VBScript and JavaScript as well as C++. It has so many advantages such as high speed, low memory overhead and the most important one, ease of use. In this brief article I'm going to describe you how to start working with ADO, for instance, how to open a recordset, query the database or execute a stored procedure. First of all let me inform you about the requirements. In this article, I used ADOTestDB.MDB as a sample database in conjunction with VC++ 6 (SP3) and ADO 2.1.In the database file I implemented two simple tables, named Student and Dept with different fields of different types and some sample data (You're able to download it from the above link). One more think that i should mention here is that I'm using import directive and gain features of smart pointers in this article. By typing the following lines in your stdafx.h you simply can do the same too. #import "msado15.dll" \ no_namespace \ rename( "EOF", "adoEOF" ) If you mention above code you'll get that I renamed the After doing so you need to initialize the COM before doing anything. In order to do that, call the Now we are going to the main part of using ADO: Making a connection to the database serverThe first step to access a data source in ADO is connecting to the data source. In order to connect to a data source you can use ADO's Connection object. The main way ADO establishes a connection is through the Connections Open member function. Take a look at the following code (Error handling omitted because of code brevity): _ConnectionPtr m_pConn; m_pConn.CreateInstance (__uuidof(Connection)); m_pConn->Open ( _bstr_t ( "Provider=Microsoft.Jet.OLEDB.4.0; Data Source = ADOTestDB.MDB" ), _bstr_t ( "" ), _bstr_t ( "" ), adModeUnknown ); That is a sample code snipped to establish a connection to the ADOTestDB.MDB via Microsoft.Jet.OLEDB.4 provider. First of all you have to define an object of type It's not bad to mention that you can also use ODBC drivers to connect to a data source, the following code will show you how to do it : m_pConn->Open (_bstr_t ("DSN=pubs;uid=sa;pwd=;"), _bstr_t (""), _bstr_t (""), adCmdUnknown ); Representing an SQL statementThere is different ways to represent an SQL statement in ADO. The most regular way is using a _CommandPtr pCommand; pCommand.CreateInstance (__uuidof (Command)); pCommand->ActiveConnection = m_pConn; // Formerly opened connection // pointer pCommand->CommandText = "Select * From Student"; As you see above, at first, we declared a Command object then instantiated it. As a next step, we set the As our command text is a query, by issuing, it would return a set of rows which we should store somewhere. For this purpose we will define a Now, we are going to execute this command, but let me mention something as before. There is two ways to execute a command in ADO, first is through the Command objects _RecordsetPtr pRecordset; pRecordset.CreateInstance (__uuidof (Recordset)); pRecordset->CursorLocation = adUseClient; pRecordset->Open ( (IDispatch *) pCommand, vtMissing, adOpenStatic, adLockBatchOptimistic, adCmdUnknown); In the snipped code we first defined an object of type Manipulating the DataAt this point, we are going to make some changes to the data. One of the fields in Student table is SocialSecNo which shows each students social security number, consider by some problem the government faced, it has to change the social security numbers starting with '45' to something like '77'. So, we have to change all the SocialSecNo starting with '45' to '77'.In order to do this we filter the current recordset for all SocialSecNo starting with '45'. Moreover, we'll set Here you might think that its not really efficient to do something such as the following, and it's somehow correct depending on the situation but my most important purpose here is, introducing different capabilities of ADO, so don't think about efficiency and injoy using ADO's features. The code for manipulating data looks like this: pRecordset->Fields->GetItem ("StudentNo")->Properties-> GetItem ("Optimize")->Value = VARIANT_TRUE; pRecordset->Sort = "Name"; pRecordset->Filter = "SocialSecNo LIKE '45*'"; while (!pRecordset->GetadoEOF()) { CString str = (char *) (_bstr_t) pRecordset->Fields-> GetItem("SocialSecNo")->Value; str = "77" + str.Right(str.GetLength() - 2); pRecordset->Fields->GetItem("SocialSecNo")->Value = (_bstr_t) str; pRecordset->MoveNext(); } pRecordset->Filter = (long) adFilterNone; In the above code at first we set the Updating the dataThere are generally two ways of updating the data in ADO. The first method is immediate update, it does mean that you make changes directly to the recordset and therefore data source as soon as you issue the In our example, we're using Batch mode so you can propagate changes with the following simple line of code: pRecordset->BatchUpdate (adAffectAll );
Now you learnt how to open and query for some data and then manipulation and update them. But there are really many more things in ADO which you must know about, one of the most important one among them is called stored procedures and parameterized commands. Executing an Stored Procedure with input parametersCalling an stored procedure is as easy as opening a new recordset such as the one we did in this article formerly. There is just some minor additions for creating input parameters and assigning their values, which we're going to discuss in the following lines. There are two general ways of passing parameters in ADO, first one is through Parameter object and the second one is via Here, I'll describe first methods for you. The following lines of code shows you how to set the input parameters and execute the _CommandPtr pCommand; _ParameterPtr pParam1, pParam2; CString str("Ma%"); pCommand.CreateInstance(__uuidof(Command)); pCommand->ActiveConnection = m_pConn; //Its the connection pointer //we opened formerly pCommand->CommandText = "Query1"; pCommand->CommandType = adCmdStoredProc; pParam1 = pCommand->CreateParameter ( _bstr_t ("DeptID"), adTinyInt, adParamInput, sizeof (BYTE), _variant_t ( long (11))); pCommand->Parameters->Append ( pParam1); pParam2 = pCommand->CreateParameter ( _bstr_t ("Name"), adVarChar, adParamInput, str.GetLength (), (_bstr_t) str); pCommand->Parameters->Append ( pParam2); _RecordsetPtr pRecordset; pRecordset.CreateInstance(__uuidof(Recordset)); pRecordset = pCommand->Execute(NULL, NULL, adCmdStoredProc); At the beginning, create a Command object then set the After specifying arguments, the created parameters respectively will be assigned to the pParam1 and pParam2.The created parameters then should be added (Appended) to the Parameters collection of our Command object, so as to do that we call the Append method for each Parameter object over Parameters collection. Now, your command is ready for execution. If you mention to the Error handling mechanismIn all codes snipped in this article so far, I didn't care about the error handling because of code brerity.At this point, I'm going to mention one simple example of error handling that you can use in all over your program wherever you use some ADO's critical functions. Generally, becuase ADO made of COM objects so it produces exceptions of type try { HRESULT hr = m_pConn.CreateInstance(__uuidof(Connection)); if (FAILED( hr )) AfxMessageBox( "Can't create an intance of ADO.Connection" ); if (FAILED( m_pConn->Open( _bstr_t( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = ADOTestDB.MDB"), _bstr_t( "" ), _bstr_t( "" ), adModeUnknown ))) AfxMessageBox( "Can't open datasource" ); ... ... ... m_pConn->Close(); } catch( _com_error &e ) { _bstr_t bstrSource(e.Source()); _bstr_t bstrDescription(e.Description()); TRACE( "Exception thrown for classes generated by #import" ); TRACE( "\tCode = %08lx\n", e.Error()); TRACE( "\tCode meaning = %s\n", e.ErrorMessage()); TRACE( "\tSource = %s\n", (LPCTSTR) bstrSource); TRACE( "\tDescription = %s\n", (LPCTSTR) bstrDescription); } catch (...) { TRACE ( "*** Unhandled Exception ***" ); } Consider in the above code the CommentsIt was a brief explanation of some ADO features. There are really a plenty of other things in ADO which you should learn if you want to become an expert in this subject. Here, I tried to give you some clues to start learning ADO and developing useful applications using it, I'm also working to issue more articles in near future about this subject, discussing more interesting and unique features. If you have any suggestions ,recommendation or questions please feel free to ask it. I would be glad to hear the article's weaknesses as well as usefulness. You can reach me using email at shokuie@hotmail.com.
| ||||||||||||||||||||