(1)、引入ADO類
#import "c:/program files/common files/system/ado/msado15.dll" no_namespace rename ("EOF", "adoEOF")
(2)、初始化COM
在MFC中可以用AfxOleInit();非MFC環境中用:
CoInitialize(NULL);CoUnInitialize();
(3)#import 包含後就可以用3個智能指針了:_ConnectionPtr、_RecordsetPtr和_CommandPtr
1.連接配接和關閉資料庫(1)連接配接
例子:連接配接Access資料庫
m_pConnection.CreateInstance(__uuidof(Connection));try {// 打開本地Access庫Demo.mdbm_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;DataSource=Demo.mdb","","",adModeUnknown);}catch(_com_error e){AfxMessageBox("資料庫連接配接失敗,确認資料庫Demo.mdb是否在目前路徑下!");return FALSE;}
(2)、關閉
//如果資料庫連接配接有效
if(m_pConnection->State) m_pConnection->Close();m_pConnection= NULL;
(3)、設定連接配接時間//設定連接配接時間-----------------------------------
pConnection->put_ConnectionTimeout(long(5));
2.打開一個結果集
(1)打開,首先建立一個_RecordsetPtr執行個體,然後調用Open()得到一條SQL語句的執行結果
_RecordsetPtrm_pRecordset;m_pRecordset.CreateInstance(__uuidof(Recordset));// 在ADO操作中建議語句中要常用try...catch()來捕獲錯誤資訊,// 因為它有時會經常出現一些意想不到的錯誤。jingzhou xutry{m_pRecordset->Open("SELECT * FROM DemoTable",// 查詢DemoTable表中所有字段m_pConnection.GetInterfacePtr(), // 擷取庫接庫的IDispatch指針adOpenDynamic,adLockOptimistic,adCmdText);}catch(_com_error *e){AfxMessageBox(e->ErrorMessage());}
(2)關閉結果集
m_pRecordset->Close();
3.操作一個結果集
(1)、周遊(讀取)
a)、用pRecordset->adoEOF來判斷資料庫指針是否已經移到結果集的末尾了;m_pRecordset->BOF判斷是否 在第一條記錄前面:
while(!m_pRecordset->adoEOF){var = m_pRecordset->GetCollect("Name");if(var.vt != VT_NULL)strName = (LPCSTR)_bstr_t(var);var = m_pRecordset->GetCollect("Age");if(var.vt != VT_NULL)strAge = (LPCSTR)_bstr_t(var);m_AccessList.AddString( strName + " --> "+strAge );m_pRecordset->MoveNext();}
b)、取得一個字段的值的辦法有兩種辦法
一是
//表示取得第0個字段的值
m_pRecordset->GetCollect("Name");
或者
m_pRecordset->GetCollect(_variant_t(long(0));
二是
pRecordset->get_Collect("COLUMN_NAME");
或者
pRecordset->get_Collect(long(index));
(2)、添加
a)、調用m_pRecordset->AddNew();
b)、調用m_pRecordset->PutCollect();給每個字段指派
c)、調用m_pRecordset->Update();确認
(3)、修改
(4)、删除
a)、把記錄指針移動到要删除的記錄上,然後調用Delete(adAffectCurrent)
try{// 假設删除第二條記錄m_pRecordset->MoveFirst();m_pRecordset->Move(1); // 從0開始m_pRecordset->Delete(adAffectCurrent); // 參數adAffectCurrent為删除目前記錄m_pRecordset->Update();}catch(_com_error *e){AfxMessageBox(e->ErrorMessage());}
4.直接執行SQL語句,除了要用到結果集其餘的大部分功能都可以直接用SQL語言實作
(1)、用_CommandPtr和_RecordsetPtr配合
_CommandPtrm_pCommand;m_pCommand.CreateInstance(__uuidof(Command));// 将庫連接配接賦于它m_pCommand->ActiveConnection = m_pConnection; // SQL語句m_pCommand->CommandText = "SELECT * FROM DemoTable"; // 執行SQL語句,傳回記錄集m_pRecordset = m_pCommand->Execute(NULL, NULL,adCmdText);
(2)、直接用_ConnectionPtr執行SQL語句
_RecordsetPtr Connection15::Execute ( _bstr_t CommandText, VARIANT * RecordsAffected, long Options ) 其中CommandText是指令字串,通常是SQL指令。 參數RecordsAffected是操作完成後所影響的行數, 參數Options表示CommandText中内容的類型,Options可以取如下值之一: adCmdText:表明CommandText是文本指令 adCmdTable:表明CommandText是一個表名 adCmdProc:表明CommandText是一個存儲過程 adCmdUnknown:未知例子:_variant_t RecordsAffected;m_pConnection->Execute("UPDATE users SET old = old+1",&RecordsAffected,adCmdText);
5.調用存儲過程
(1)、利用_CommandPtr
_CommandPtrm_pCommand;m_pCommand.CreateInstance(__uuidof(Command));m_pCommand->ActiveConnection = m_pConnection; // 将庫連接配接賦于它m_pCommand->CommandText = "Demo"; m_pCommand->Execute(NULL,NULL, adCmdStoredProc);
(2)、直接用_ConnectionPtr直接調用(見4.(2))
6.周遊資料庫中的所有表名
_ConnectionPtr m_pConnect; _RecordsetPtr pSet; HRESULT hr; try { hr = m_pConnect.CreateInstance("ADODB.Connection"); if(SUCCEEDED(hr)) { CString dd; dd.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s",file); hr = m_pConnect->Open((_bstr_t)dd,"","",adModeUnknown); pSet = m_pConnect->OpenSchema(adSchemaTables); while(!(pSet->adoEOF)) { //擷取表格 _bstr_t table_name = pSet->Fields->GetItem("TABLE_NAME")->Value;//擷取表格類型 _bstr_t table_type = pSet->Fields->GetItem("TABLE_TYPE")->Value;//過濾一下,隻輸出表格名稱,其他的省略if ( strcmp(((LPCSTR)table_type),"TABLE")==0){CString tt;tt.Format("%s",(LPCSTR)table_name); AfxMessageBox(tt); } pSet->MoveNext(); } pSet->Close(); } m_pConnect->Close(); }catch(_com_error e)///捕捉異常 { CString errormessage; errormessage.Format("連接配接資料庫失敗!rn錯誤資訊:%s",e.ErrorMessage());AfxMessageBox(errormessage);return -1;}
7.周遊一個表中的所有字段
Field * field = NULL;HRESULT hr;Fields * fields = NULL;hr = m_pRecordset->get_Fields (&fields);//得到記錄集的字段集和 if(SUCCEEDED(hr)) fields->get_Count(&ColCount);//得到記錄集的字段集合中的字段的總個數for(i=0;i
Item[i]->get_Name(&bstrColName);//得到記錄集//中的字段名strColName=bstrColName;nameField = strColName;m_FieldsList.AddString(nameField);}if(SUCCEEDED(hr))fields->Release();//釋放指針
附:
1、_variant_t
(1)、一般傳給這3個指針的值都不是MFC直接支援的資料類型,而要用_variant_t轉換一下
_variant_t(XX)可以把大多數類型的變量轉換成适合的類型傳入:
(2)、_variant_t var;
_variant_t -> long: (long)var;_variant_t -> CString: CString strValue = (LPCSTR)_bstr_t(var);CString -> _variant_t: _variant_t(strSql);
2、BSTR寬字元串與CString互相轉換
BSTR bstr;CString strSql;CString -> BSTR: bstr = strSql.AllocSysString();BSTR -> CString: strSql = (LPCSTR)bstr;
3、_bstr_t與CString互相轉換
_bstr_t bstr;CString strSql;CString -> _bstr_t: bstr = (_bstr_t)strSql;_bstr_t -> CString: strSql = (LPCSTR)bstr;
4、關于時間
Access:表示時間的字元串#2004-4-5#
Sql:表示時間的字元串''2004-4-5''
DateField(時間字段) select * from my_table where DateField > #2004-4-10#