#import "c:/program files/common files/system/ado/msdao15.dll"
no_namespaces rename("EOF","adoEOF")
_ConnectionPtr, this is the connection interface. It is similar to CDatabase or CDaoDatabase. It basicly works the same way. You create an instance of it, point it to a database either through ODBC or a provider, and you open it. Look how similar it is to CDaoDatabase:
CDaoDatabase MyDb = new CDaoDatabase();
m_DaoServerDB.Open(NULL,FALSE,FALSE,"ODBC;DSN=SAMS_SVR;UID=admin;PWD=admin");
Now using ADO:
_ConnectionPtr MyDb;
MyDb.CreateInstance(__uuidof(Connection));
MyDb->Open("DSN=SAMS_SVR;UID=admin;PWD=admin","","",-1);
_RecordsetPtr, This is the recordset interface. It is similar to CDaoRecordset. Again when you see how similar it is to CDaoRecordset you will wonder why you did not use it sooner. Lets see how they work: (We will use the database and the connection above in our example.)
CDaoRecordset MySet = new CDaoRecordset(MyDb);
MySet->Open(AFX_DAO_USE_DEFAULT_TYPE,"SELECT * FROM some_table");
Now using ADO:
_RecordsetPtr MySet;
MySet.CreateInstance(__uuidof(Recordset));
MySet->Open("SELECT * FROM some_table",
MyDb.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
ADO is slightly more involved. But with some of the added benifits you get with ADO (most of which are beyond the scope of this article) ADO is worth the extra effort here.
Now that we have a Connection and a Recordset, lets get some data out of it. In both cases we are going to fill a list box with information in the recordset. (Assuming we have a listbox called m_List)
DAO:
VARIANT *vFieldValue;
COleVariant covFieldValue;
CString Holder;
while(!MySet->IsEOF())
{
MySet->GetFieldValue("FIELD_1", covFieldValue);
vFieldValue = (LPVARIANT)covFieldValue;
if(vFieldValue->vt!=VT_NULL)
{
Holder.Format("%s",vFieldValue->pbVal);
m_List.AddString(Holder);
}
MySet.MoveNext();
}
ADO:
_variant_t Holder
while(!MySet->adoEOF)
{
Holder = MySet->GetCollect("FIELD_1");
if(Holder.vt!=VT_NULL)
m_List.AddString((char*)_bstr_t(Holder));
MySet->MoveNext();
}
A special note. There is NO documentation for the GetCollect method. I have searched everywhere, and no one mentioned it. the other method of retrieving data would be:
Holder = MySet->GetFields->Field->(_variant_t(FieldNumber))->Value;
I like the GetCollect better.
本文主要对比了ADO和DAO在数据库操作上的使用。介绍了连接数据库和打开记录集的操作,展示了二者代码的相似性。还说明了从记录集中获取数据并填充列表框的方法,指出ADO虽更复杂,但有额外优势,同时提到ADO的GetCollect方法缺乏文档。
730

被折叠的 条评论
为什么被折叠?



