一、浏览记录:
1.创建对话框窗口
添加一个listControl ,并关联一个变量“m_list”
2.在头文件“MiniMsDlg.h”导入msado15.dll动态链接库文件
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
3.编写函数接口:
3-1:定义连接对象和记录集对象
_ConnectionPtr m_pConnection; _RecordsetPtr m_pRecordset;
3-2:连接数据库Access数据库
在OnInitDialog函数中添加如下代码:
AfxOleInit();
LV_COLUMN listColumn; TCHAR *listTitle[2]={_T("学号"),_T("姓名")}; int intColCx[2]={100,120}; listColumn.mask=LVCF_FMT|LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM; listColumn.fmt=LVCFMT_LEFT; for(int ncol=0;ncol<2;ncol++){ listColumn.cx=intColCx[ncol]; listColumn.iSubItem=ncol; listColumn.pszText=listTitle[ncol]; m_list.InsertColumn(ncol,&listColumn); }
m_list.SetExtendedStyle(LVS_EX_FULLROWSELECT);
m_pConnection.CreateInstance(__uuidof(Connection)); CString strConn=_T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\demo\\myAccess.mdb"); try{ m_pConnection->Open((_bstr_t)strConn,_T(""),_T(""),adModeUnknown); }catch(_com_error &e){
AfxMessageBox((LPCTSTR)e.Description()); m_pConnection=NULL; return TRUE; } catch(...){ AfxMessageBox(_T("未知错误")); m_pConnection=NULL; return TRUE; }
//记录集对象 m_pRecordset.CreateInstance(__uuidof(Recordset)); LPCTSTR lpSql=_T("select * from Students order by StudentID"); m_pRecordset->Open((_variant_t)lpSql,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText); if(m_pRecordset==NULL){ AfxMessageBox(_T("读取数据库失败")); return TRUE; }
m_list.DeleteAllItems();
int nitem=0; _variant_t id,name; CString strId,strName; while(!m_pRecordset->adoEOF){ id=m_pRecordset->GetCollect(_T("StudentId")); name=m_pRecordset->GetCollect(_T("StudentName"));
strId.Format(_T("%d"),id.intVal); strName=(LPCTSTR)_bstr_t(name); //AfxMessageBox(_T("11111")); m_list.InsertItem(nitem,strId); m_list.SetItemText(nitem,1,strName); m_list.SetItemData(nitem,id.intVal); nitem++; m_pRecordset->MoveNext(); }
m_pRecordset->Close();
以上代码亲测可行。