|
5. 記錄集的遍歷、更新
根據(jù)我們剛才通過執(zhí)行SQL命令建立好的users表,它包含四個字段:ID,username,old,birthday 以下的代碼實現(xiàn):打開記錄集,遍歷所有記錄,刪除第一條記錄,添加三條記錄,移動光標到第二條記錄, 更改其年齡,保存到數(shù)據(jù)庫。 _variant_t vUsername,vBirthday,vID,vOld; _RecordsetPtr m_pRecordset; m_pRecordset.CreateInstance("ADODB.Recordset"); m_pRecordset->Open("SELECT * FROM users", _variant_t((IDispatch*)m_pConnection,true), adOpenStatic, adLockOptimistic, adCmdText); while(!m_pRecordset->adoEOF) { vID = m_pRecordset->GetCollect(_variant_t((long)0));///取得第1列的值,從0開始計數(shù), ///你也可以直接給出列的名稱,如下一行 vUsername = m_pRecordset->GetCollect("username");///取得username字段的值 vOld = m_pRecordset->GetCollect("old"); vBirthday = m_pRecordset->GetCollect("birthday"); ///在DEBUG方式下的OUTPUT窗口輸出記錄集中的記錄 if(vID.vt != VT_NULL && vUsername.vt != VT_NULL && vOld.vt != VT_NULL && vBirthday.vt != VT_NULL) TRACE("id:%d,姓名:%s,年齡:%d,生日:%s\r\n", vID.lVal, (LPCTSTR)(_bstr_t)vUsername, vOld.lVal, (LPCTSTR)(_bstr_t)vBirthday); m_pRecordset->MoveNext();///移到下一條記錄 } m_pRecordset->MoveFirst();///移到首條記錄 m_pRecordset->Delete(adAffectCurrent);///刪除當前記錄 ///添加三條新記錄并賦值 for(int i=0;i<3;i++) { m_pRecordset->AddNew();///添加新記錄 m_pRecordset->PutCollect("ID",_variant_t((long)(i+10))); m_pRecordset->PutCollect("username",_variant_t("葉利欽")); m_pRecordset->PutCollect("old",_variant_t((long)71)); m_pRecordset->PutCollect("birthday",_variant_t("1930-3-15")); } m_pRecordset->Move(1,_variant_t((long)adBookmarkFirst));///從第一條記錄往下移動一條記錄,即移動到第二條記錄處 m_pRecordset->PutCollect(_variant_t("old"),_variant_t((long)45));///修改其年齡 m_pRecordset->Update();///保存到庫中 備注:多次查詢可把查詢過程做成一個函數(shù)ExecuteSQL讓m_pRecordset獲得連接指針 m_pConnection查詢結果 void ExecuteSQL(_ConnectionPtr m_pConnection, _RecordsetPtr m_pRecordset,CString strSql) { //執(zhí)行Select 語句 BSTR bstrSQL = strSql.AllocSysString(); try { m_pRecordset->Open(bstrSQL,(IDispatch*)m_pConnection,adOpenDynamic,adLockOptimistic,adCmdText); //adOpenDynamic:動態(tài) adLockOptimistic樂觀封鎖法 adCmdText:文本查詢語句 } catch(_com_error error) { CString errorMessage; errorMessage.Format("%s",(LPTSTR)error.Description()); AfxMessageBox(errorMessage); } } //出錯處理: 3127——沒有找到目標表 3092——目標表已經(jīng)存在 例如: catch(const _com_error e) { AfxMessageBox(e.Description()); long errorCode=e.WCode(); if(3127==errorCode) AfxMessageBox("表不存在"); if(3092==errorCode) AfxMessageBox("表已經(jīng)存在"); return FALSE; }
|