本文共 1670 字,大约阅读时间需要 5 分钟。
1.在StdAfx.h最后面增加
#include#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","rsEOF")
2.在***App Class中InitinStance事件中添加
if(!AfxOleInit()) { AfxMessageBox("OLE初始化出错!"); return FALSE; }注意:添加时位置最好在紧接AfxEnableControlContainer()之后
3.在OnButton事件中添加
//查询功能void CDATABASE_ADO_TESTDlg::OnButton1() { // TODO: Add your control notification handler code here UpdateData(TRUE); m_strName=""; m_strMajor=""; m_strSex=""; m_iAge=20; UpdateData(FALSE); if(m_strID==0) { MessageBox("输入ID不能为空!"); return; } //创建结果集实例 _RecordsetPtr pRS; if(FAILED(pRS.CreateInstance("ADODB.Recordset"))) { AfxMessageBox("Create Instance failed"); return; } //创建SQL查询语句 CString strSRC=GetConnStr(); CString strSQL; strSQL.Format("select * from Student where StudentID=%d",m_strID); //打开数据库,ADO::Open(sql语句,数据库路径,光标类型 <常量> ,锁定类型,sql类型),在文章最后各常量都有列举 if(FAILED(pRS->Open((_variant_t)strSQL,(_variant_t)strSRC,adOpenStatic,adLockOptimistic,adCmdText))) { AfxMessageBox("Can not open Database!"); pRS->Release(); return; } //历遍所有结果集记录 while(!pRS->rsEOF) { _variant_t varName; varName=pRS->GetCollect("Name"); m_strName=(char *)_bstr_t(varName); varName=pRS->GetCollect("Sex"); m_strSex=(char *)_bstr_t(varName); varName=pRS->GetCollect("Major"); m_strMajor=(char *)_bstr_t(varName); varName=pRS->GetCollect("Age"); m_iAge=atoi((char *)_bstr_t(varName)); pRS->MoveNext(); } //更新数据 UpdateData(FALSE); pRS.Release();} 常量>注意:1.pRS.Release使用的是释放单元内存,而不是->,
创建实例的时候使用'.',而不是用->
2.如果无法打开,或报错,请使用
try { } catch (_com_error &e) { AfxMessageBox((char*)e.Description()); }进行调试
3.代码中用到的(_variant_t)是将任意变量转换为最合适的类型
4.ADO的光标类型,ADO的锁定类型,ADO的光标服务位置等定义,请参见
转载地址:http://mngpb.baihongyu.com/