myset->open(afx_dao_use_default_type,"select * from t_samp");
now using ado:
代码8:使用_recordsetptr执行sql语句
_recordsetptr myset;
myset.createinstance(__uuidof(recordset));
myset->open("select * from some_table",
mydb.getinterfaceptr(),adopendynamic,adlockoptimistic,adcmdtext);
现在我们已经有了一个数据连接和一个记录集,接下来就可以使用数据了。从以下代码可以看到,使用ado的_recordsetptr接口,就不需要象dao那样频繁地使用大而复杂的数据结构variant,并强制转换各种数据类型了,这也是ado的优点之一。假定程序有一个名称为m_list的的listbox控件,下面代码我们用_recordsetptr接口获取记录集数据并填充这个listbox控件:
代码9:使用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();
}
代码10:使用ado访问数据
_variant_t holder
try{
while(!myset->adoeof)
{
holder = myset->getcollect("field_1");
if(holder.vt!=vt_null)
m_list.addstring((char*)_bstr_t(holder));
myset->movenext();
}
}
catch(_com_error * e)
{
cstring error = e->errormessage();
afxmessagebox(e->errormessage());
}
catch(...)
{
messagebox("ado发生错误!");
}
必须始终在代码中用try和catch来捕获ado错误,否则ado错误会使你的应用程序崩溃。当ado发生运行时错误时(如数据库不存在),ole db数据提供者将自动创建一个_com_error对象,并将有关错误信息填充到这个对象的成员变量.
6、使用_commandptr接口
_commandptr接口返回一个recordset对象,并且提供了更多的记录集控制功能,以下代码示例了使用_commandptr接口的方法:
代码11:使用_commandptr接口获取数据
_commandptr pcommand;
_recordsetptr myset;
pcommand.createinstance(__uuidof(command));
pcommand->activeconnection=mydb;
pcommand->commandtext="select * from some_table";
pcommand->commandtype=adcmdtext;
pcommand->parameters->refresh();
myset=pcommand->execute(null,null,adcmdunknown);
_variant_t thevalue = myset->getcollect("field_1");
cstring svalue=(char*)_bstr_t(thevalue);
7、关于数据类型转换
由于com对象是跨平台的,它使用了一种通用的方法来处理各种类型的数据,因此cstring 类和com对象是不兼容的,我们需要一组api来转换com对象和c++类型的数据。_vatiant_t和_bstr_t就是这样两种对象。它们提供了通用的方法转换com对象和c++类型的数据。
8、小结