資源描述:
《MFC下ADO連接數(shù)據(jù)庫(mdb和sql2000)(附帶源碼)》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、MFC使用ADO對(duì)象開發(fā)數(shù)據(jù)庫應(yīng)用程序需要一個(gè)ListConstrol控件設(shè)置為其步驟一般分為:(1)引入ADO動(dòng)態(tài)庫文件(2)初始化COM環(huán)境(3)連接數(shù)據(jù)庫操作數(shù)據(jù)表說明:本數(shù)據(jù)庫使用acess2000制作,名字為“shujuku.mdb”。內(nèi)含一個(gè)表,命名為“表1”。在stdafx.h添加以下代碼引入ADO動(dòng)態(tài)庫文件#import"C:ProgramFilesCommonFilesSystemadomsado15.dll"no_namespacerename("EOF","adoEOF
2、")rename("BOF","adoBOF")初始化COM環(huán)境::CoInitialize(NULL);//在app類中的InitInstance函數(shù)中添加::CoUninitialize();//在app類中的InitInstance函數(shù)的最后(return之前)添加,釋放COM環(huán)境首先先在dlg頭文件中先聲明這兩個(gè)智能指針,通過這些指針可以很容易的創(chuàng)建和刪除ADO對(duì)象。_ConnectionPtrm_pConnection;_RecordsetPtrm_pRecordset;接下來在dlg類中添加
3、函數(shù)voidOnInitADOConn()voidCMy1Dlg::OnInitADOConn(){try{//創(chuàng)建連接對(duì)象實(shí)例m_pConnection.CreateInstance("ADODB.Connection");//設(shè)置連接字符串(2000的在代碼中有!)CStringstrConnect="DRIVER={MicrosoftAccessDriver(*.mdb)};uid=;pwd=;DBQ=shujuku.mdb;";//使用Open方法連接數(shù)據(jù)庫m_pConnection->Ope
4、n((_bstr_t)strConnect,"","",adModeUnknown);}catch(_com_errore){AfxMessageBox(e.Description());}}在dlg類中在添加voidExitConnect()函數(shù)voidCMy1Dlg::ExitConnect(){//關(guān)閉記錄集和連接if(m_pRecordset!=NULL)m_pRecordset->Close();m_pConnection->Close();}在dlg類的OnInitDialog函數(shù)中添加如下
5、代碼,設(shè)置列表視圖的風(fēng)格和標(biāo)題(寫在最后)m_Grid.SetExtendedStyle(LVS_EX_FLATSB
6、LVS_EX_FULLROWSELECT
7、LVS_EX_HEADERDRAGDROP
8、LVS_EX_ONECLICKACTIVATE
9、LVS_EX_GRIDLINES);m_Grid.InsertColumn(0,"編號(hào)",LVCFMT_LEFT,110,0);m_Grid.InsertColumn(1,"姓名",LVCFMT_LEFT,110,1);m_Grid.InsertColum
10、n(2,"性別",LVCFMT_LEFT,110,2);m_Grid.InsertColumn(3,"學(xué)歷",LVCFMT_LEFT,110,3);AddToGrid();在dlg類中添加voidAddToGrid()函數(shù)voidCMy1Dlg::AddToGrid(){//連接數(shù)據(jù)庫OnInitADOConn();//設(shè)置查詢字符串_bstr_tbstrSQL="select*from表1orderby編號(hào)desc";//創(chuàng)建記錄集指針對(duì)象實(shí)例m_pRecordset.CreateInstance(_
11、_uuidof(Recordset));//打開記錄集m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);while(!m_pRecordset->adoEOF){m_Grid.InsertItem(0,"");m_Grid.SetItemText(0,0,(char*)(_bstr_t)m_pRecordset->GetCollect("編號(hào)"));m_
12、Grid.SetItemText(0,1,(char*)(_bstr_t)m_pRecordset->GetCollect("姓名"));m_Grid.SetItemText(0,2,(char*)(_bstr_t)m_pRecordset->GetCollect("性別"));m_Grid.SetItemText(0,3,(char*)(_bstr_t)m_pRecordset->GetCollect("學(xué)歷"));//將記錄集指針移動(dòng)到