Microsoft Office Access是由微軟發布的關系數據庫管理系統。Access數據庫常應用于小型軟件系統中,比如:生產管理、銷售管理、庫存管理等各類企業管理軟件,其最大的優點是:簡單易學、使用靈活。
下面我們結合實例來詳細說明,在VC++ MFC中,如何使用Access數據庫文件進行數據的存儲,如何實現對數據庫中數據的查詢、插入、更新和刪除等操作。
(實例可在我的CSDN資源中下載:[http://download.csdn.net/detail/margin1988/8235865](http://download.csdn.net/detail/margin1988/8235865))
首先,怎樣創建一個可供VC++ MFC程序使用的Access數據庫,并在該數據庫中創建數據表呢?
> 第一步:打開Microsoft Office Access軟件,點擊“空白數據庫”;
> 
> 第二步:設置預創建空白數據庫的文件名和文件類型(文件名:point32.mdb,文件類型:Microsoft Office Access 2000 數據庫(*.mdb));
> 
> 第三步:“創建”空白數據庫;
> 
> 第四步:為該數據庫“設置數據庫密碼”(本例中密碼設置為:1234);
> 
> 第五步:在該數據庫中創建一張表,例如:TestTab(編號,姓名,性別,年齡);
> 
> 第六步:表創建完成后,保存并關閉數據庫,然后將該數據庫文件(point32.mdb)剪切到你的VC++程序debug或release目錄中,則準備工作完成。
其次,在VC++ MFC中編寫對該數據庫中TestTab表進行數據查詢、插入、更新、刪除等操作的方法:
(1)導入才用ado方式訪問Access數據庫所需的DLL
~~~
#import "C:\Program Files\Common Files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")//ado訪問ACCESS數據庫必需
~~~
(2)在程序的入口函數中,初始化OLE以支持應用程序
~~~
AfxOleInit();
~~~
(3)獲取應用程序(EXE)所在路徑
~~~
CString path;//應用程序所在路徑
char filepath[256];
char* pPath;
GetModuleFileName(AfxGetInstanceHandle(),filepath,256);
pPath = strrchr(filepath,'\\');
*pPath = 0;
path = filepath;
~~~
(4)**創建**數據庫訪問連接字符串
~~~
char* PtConnectStr;//數據庫連接字符串
CString connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
connstr += path;
connstr += "\\point32.mdb";
connstr += ";Jet OLEDB:Database Password='1234'";
PtConnectStr = connstr.GetBuffer(0);
~~~
(5)**查詢**TestTab表中數據方法實現
~~~
//查詢表中數據,并顯示在List Control控件中
void CPoint32Dlg::ReadUserInfo()
{
//select
m_list.DeleteAllItems();//清空列表
_ConnectionPtr m_pConnection;
_RecordsetPtr m_pRecordset;
try
{
m_pConnection.CreateInstance(__uuidof(Connection));
m_pConnection->Open(PtConnectStr,"","",adModeUnknown);
}
catch(_com_error e)
{
CString errormessage;
errormessage.Format("數據庫連接失敗.\r錯誤信息:%s",e.ErrorMessage());
//AfxMessageBox(errormessage);
MessageBox(errormessage,"連接失敗",MB_ICONEXCLAMATION);
if(m_pConnection->State)
m_pConnection->Close();
return;
}
try
{
//獲取數據,放在數據集中
CString cmd;
cmd.Format("SELECT * FROM TestTab");
m_pRecordset.CreateInstance("ADODB.Recordset");
m_pRecordset->Open(cmd.GetBuffer(),
_variant_t((IDispatch*)m_pConnection,true),
adOpenStatic,
adLockOptimistic,
adCmdText);
//處理數據,并顯示
_variant_t varbuffer;
long index = 0;//注意:必須是long類型
int countItem = 0;
CString str;
while(!m_pRecordset->adoEOF)
{
index = 0;
//讀ID號
varbuffer = m_pRecordset->GetCollect(_variant_t(index));
if(varbuffer.vt!=VT_NULL)
{
str.Format("%d",varbuffer.lVal);
m_list.InsertItem(countItem,str.GetBuffer());
}
//讀其它的信息
while(index < 3)
{
index++;
varbuffer = m_pRecordset->GetCollect(_variant_t(index));
if(varbuffer.vt!=VT_NULL)
{
str = (LPCTSTR)(_bstr_t)varbuffer;
m_list.SetItemText(countItem,index,str.GetBuffer());
}
}
m_pRecordset->MoveNext();
countItem++;
}
}
catch(_com_error &e)
{
//AfxMessageBox(e.Description());
MessageBox(e.Description(),"數據庫操作失敗.",MB_ICONEXCLAMATION);
if(m_pRecordset->State)
m_pRecordset->Close();
if(m_pConnection->State)
m_pConnection->Close();
return;
}
if(m_pRecordset->State)
m_pRecordset->Close();
if(m_pConnection->State)
m_pConnection->Close();
}
~~~
(6)向TestTab表中**插入**數據方法實現
~~~
//向表中插入數據,并更新List Control控件中顯示的數據
void CPoint32Dlg::OnBnClickedButton1()
{
//insert
_ConnectionPtr m_pConnection;
_variant_t RecordsAffected;
try
{
m_pConnection.CreateInstance(__uuidof(Connection));
m_pConnection->Open(PtConnectStr,"","",adModeUnknown);
}
catch(_com_error e)
{
CString errormessage;
errormessage.Format("數據庫連接失敗.\r錯誤信息:%s",e.ErrorMessage());
MessageBox(errormessage," 添加失敗 ",MB_ICONEXCLAMATION);
return;
}
try
{
CString strCmd="INSERT INTO TestTab(UName,UGender,UAge) VALUES('測試者','男','30')";
for(int i=0;i<5;i++)
{
m_pConnection->Execute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);
}
}
catch(_com_error &e)
{
//AfxMessageBox(e.Description());
MessageBox(e.Description()," 添加失敗 ",MB_ICONEXCLAMATION);
if(m_pConnection->State)
m_pConnection->Close();
return;
}
if(m_pConnection->State)
m_pConnection->Close();
//MessageBox("添加成功!","消息");
m_update.EnableWindow(TRUE);
m_delete.EnableWindow(TRUE);
ReadUserInfo();
}
~~~
(7)**更新**TestTab表中數據方法實現
~~~
//更新表中數據,并更新List Control控件的顯示
void CPoint32Dlg::OnBnClickedButton3()
{
// update
_ConnectionPtr m_pConnection;
_variant_t RecordsAffected;
try
{
m_pConnection.CreateInstance(__uuidof(Connection));
m_pConnection->Open(PtConnectStr,"","",adModeUnknown);
}
catch(_com_error e)
{
CString errormessage;
errormessage.Format("數據庫連接失敗.\r錯誤信息:%s",e.ErrorMessage());
MessageBox(errormessage," 修改失敗 ",MB_ICONEXCLAMATION);
return;
}
try
{
CString strCmd="UPDATE TestTab SET [UGender]='女',[UAge]='20' WHERE [UName]='測試者'";
m_pConnection->Execute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);
}
catch(_com_error &e)
{
//AfxMessageBox(e.Description());
MessageBox(e.Description()," 修改失敗 ",MB_ICONEXCLAMATION);
if(m_pConnection->State)
m_pConnection->Close();
return;
}
if(m_pConnection->State)
m_pConnection->Close();
//MessageBox("修改成功!","消息");
ReadUserInfo();
}
~~~
(8)**刪除**TestTab表中數據及重置表中自動編號主鍵(key)方法現實
~~~
//刪除表中數據、重置自動編號(從1開始),并更新List Control控件顯示
void CPoint32Dlg::OnBnClickedButton4()
{
// delete
_ConnectionPtr m_pConnection;
_variant_t RecordsAffected;
try
{
m_pConnection.CreateInstance(__uuidof(Connection));
m_pConnection->Open(PtConnectStr,"","",adModeUnknown);
}
catch(_com_error e)
{
CString errormessage;
errormessage.Format("連接數據庫失敗!\r錯誤信息:%s",e.ErrorMessage());
MessageBox(errormessage,"刪除失敗",MB_ICONEXCLAMATION);
return;
}
try
{
//刪除表中所有數據
CString strCmd="DELETE FROM TestTab";
m_pConnection->Execute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);
//重置表中自動編號ID,使其從1開始增加(必須先刪除表中所有數據)
strCmd="ALTER TABLE TestTab ALTER COLUMN ID COUNTER(1,1)";
m_pConnection->Execute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);
}
catch(_com_error &e)
{
//AfxMessageBox(e.Description());
MessageBox(e.Description(),"刪除失敗",MB_ICONEXCLAMATION);
if(m_pConnection->State)
m_pConnection->Close();
return;
}
if(m_pConnection->State)
m_pConnection->Close();
//MessageBox("刪除成功!","完成");
m_insert.EnableWindow(TRUE);
m_update.EnableWindow(FALSE);
m_delete.EnableWindow(FALSE);
ReadUserInfo();
}
~~~
- 前言
- VC++中自定義熱鍵及響應
- CFileDialog文件對話框
- VC++中客戶區保存為BMP圖片
- VC++讀、寫注冊表
- VC++播放音頻文件和音頻數據的方法
- VC++調用Matlab編寫的DLL(混合編程)
- VC++中文件讀、寫和其他相關操作匯總
- VC++獲取系統當前時間
- VC++按鈕控件字體設置
- VC++軟件界面風格簡單美化
- VC++中一些常用的數據類型之間的相互轉化
- VC++中截取字符串的方法
- VC++中vector矢量的使用方法及隨機相關
- VC++中結構體的定義及使用
- VC++中List Control控件的使用方法介紹
- VC++中窗口過程函數及其消息發送、響應機制介紹
- VC++中Ribbon編程架構及SDI架構多視圖切換介紹
- 串口通信基礎知識及VC++實現
- VC++中單個鍵盤按鍵的響應
- VC++中的計時器及多媒體高精度計時器
- VC++編寫DLL導出函數及其調用方法
- VC++對話框(CDialog)的全屏顯示及控件居中顯示
- VC++對話框(CDialog)添加背景圖片
- VC++圖片控件(Picture Control)顯示資源位圖(BMP)、文件位圖(BMP)、其它格式文件圖片(JPG\PNG\BMP)的方法
- VC++對Access數據庫的操作(查詢、插入、更新、刪除等)