[轉]vc中使用ADO訪問access數據庫
//dbDemoConsole.cpp : Defines the entry point for the console //application./*#include "stdafx.h"int main(int argc, char* argv[]){printf("Hello World!\n");return 0;}*//*說明:環境:VC6.0工程:MFC console程序,模板是hello world(這樣它會自動生成一個main()代碼:將整段代碼替代整個cpp即可來源:網上文摘及cdsn vc.chm*//*注意:關於_RecordsetPtr1)什麼時候用close()? 對於_RecordsetPtr,如果最後一次不是執行open(select from),則不需要close!否則會有異常。 而且如果最後一次是open,必須要記住close,否則再次open會有異常 貌似在Putcollect()後面也要close(),否則再open()也會異常。2)什麼時候用Update()? Execute()這個不能用update,在putcollect()後面才要update() 不過,經測試putcollect()後面要不要update(),都可以存在數據庫中,不管後面是否沒經過update()直接就close()掉*/#include "stdafx.h"#include <iostream.h>//用#import指令引入ADO類型庫#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename ("EOF", "adoEOF")int main(int argc, char* argv[]){//使用ADO連接數據庫...//---------------------------------------------_ConnectionPtr m_pConnection; HRESULT hr;//在MFC中可以用AfxOleInit();非MFC環境中用CoInitialize CoInitialize(NULL); try{ //m_pConnection.CreateInstance(__uuidof(Connection)); //這個也行 hr=m_pConnection.CreateInstance("ADODB.Connection");///創建Connection對象 // 在ADO操作中建議語句中要常用try...catch()來捕獲錯誤信息, // 因為它有時會經常出現一些想不到的錯誤。 if(SUCCEEDED(hr)) { // 打開本地Access庫,路徑中必須用\\,如果在源目錄(不是指debug下,而是代碼文件目錄)下只要Source=testdb.mdb即可 m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\myProgramLib\\vc測試程序\\accessdb\\testdb.mdb","","",adModeUnknown); }}catch(_com_error e){ cout<<e.ErrorMessage()<<"\r\n"<<"數據庫連接失敗,確認數據庫db1.mdb是否在當前路徑下!"<<endl; return FALSE; /* CString errormessage; errormessage.Format("連接數據庫失敗!\r\n錯誤信息:%s",e.ErrorMessage()); AfxMessageBox(errormessage);///顯示錯誤信息 */} //-------------------------------------------------//建立數據集//-------------------------------------------------_RecordsetPtr m_pRecordset;m_pRecordset.CreateInstance(__uuidof(Recordset));//-------------------------------------------------//CSDN.chm測試語句//-------------------------------------------------_variant_t RecordsAffected;try{// m_pRecordset =m_pConnection->Execute("Select Count(*) AS Qty FROM MSysObjects Where MSysObjects.Name="users")",&RecordsAffected,adCmdText);// _variant_t lHave = m_pRecordset->GetCollect((long)0); //TODO: 如何判斷access是否已經存在某表了? _variant_t lHave; lHave.lVal=1; if (lHave.lVal<=0) { cout<<"table users not exists,then create it!"<<endl; ///執行SQL命令:CREATE TABLE創建表格users,users包含四個字段:整形ID,字符串username,整形old,日期型birthday m_pConnection->Execute("CREATE TABLE users(ID INTEGER,username TEXT,old INTEGER,birthday DATETIME)",&RecordsAffected,adCmdText); ///往表格裡面添加記錄 //!!對於含有引號的直接用\轉義("張三")就可以了,不要像上面的一堆''''''''張三'''''''',這個通不過,也不知道為啥?? m_pConnection->Execute("INSERT INTO users(ID,username,old,birthday) valueS (1, "張三",22,"1970/1/1")",&RecordsAffected,adCmdText); ///將所有記錄old字段的值加一 m_pConnection->Execute("UPDATE users SET old = old+1",&RecordsAffected,adCmdText); //m_pRecordset->Update(); //這個不能用update,因為不是putcollect() ///執行SQL統計命令得到包含記錄條數的記錄集 m_pRecordset = m_pConnection->Execute("SELECT COUNT(*) FROM users",&RecordsAffected,adCmdText); _variant_t vIndex = (long)0; _variant_t vCount = m_pRecordset->GetCollect(vIndex);///取得第一個字段的值放入vCount變量 //message.Format("共有%d條記錄",); cout<<"共有"<<vCount.lVal<<"條記錄"<<endl; m_pRecordset->Close();///關閉記錄集 --因為有select,這邊必須close,後面才能夠再open } else { cout<<"table users exists,then not create it!"<<endl; }}catch(_com_error *e){ cout<<e->ErrorMessage()<<endl;}//根據我們剛才通過執行SQL命令建立好的users表,它包含四個字段:ID,username,old,birthday//以下的代碼實現:打開記錄集,遍歷所有記錄,刪除第一條記錄,添加三條記錄,移動光標到第二條記錄,更改其年齡,保存到數據庫。_variant_t vUsername,vBirthday,vID,vOld;//m_pConnection.GetInterfacePtr() 或 _variant_t((IDispatch*)m_pConnection,true)m_pRecordset->Open("SELECT * FROM users",m_pConnection.GetInterfacePtr(),adOpenStatic,adLockOptimistic,adCmdText);if(!m_pRecordset->BOF)m_pRecordset->MoveFirst();else{cout<<"表內數據為空"<<endl;return 1;}while(!m_pRecordset->adoEOF)///這裡為什麼是adoEOF而不是EOF呢?還記得rename("EOF","adoEOF")這一句嗎?{ vID = m_pRecordset->GetCollect(_variant_t((long)0));///取得第1列的值,從0開始計數,你也可以直接給出列的名稱,如下一行 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); cout<<"id:"<<vID.lVal<<",姓名:"<<(LPCTSTR)(_bstr_t)vUsername<<",年齡:"<<vOld.lVal<<",生日:"<<(LPCTSTR)(_bstr_t)vBirthday<<"\r\n"; 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();///保存到庫中 --好像有沒update()都可以更新到數據庫來的??//-------------------------------------------------//CSDN.chm測試語句 <end>//-------------------------------------------------//--------------------------------------------------//讀取數據//--------------------------------------------------/* _variant_t var; char *strID,*strX,*strY; float X,Y; // 讀入庫中各字段並加入列表框中 while(!m_pRecordset->adoEOF) { var = m_pRecordset->GetCollect("ID"); if(var.vt != VT_NULL) strID= _com_util::ConvertBSTRToString((_bstr_t)var); //_variant_t轉字符串 var = m_pRecordset->GetCollect("WNX"); if(var.vt != VT_NULL) strX=_com_util::ConvertBSTRToString((_bstr_t)var); var = m_pRecordset->GetCollect("WNY"); if(var.vt != VT_NULL) strY=_com_util::ConvertBSTRToString((_bstr_t)var); cout<<strID<<"is"<<strX<<" "<<strY<<endl; m_pRecordset->MoveNext(); } }catch(_com_error *e){ cout<<e->ErrorMessage()<<endl;} *///--------------------------------------------------//關閉數據集// m_pRecordset->Close();m_pRecordset = NULL; //--------------------------------------------------//關閉數據庫連接//--------------------------------------------------if(m_pConnection->State) m_pConnection->Close();m_pConnection= NULL;return 0;}