引入库:msado15.dll
//初始化与定义对象
CoInitialize(NULL); //初始化Com库
_ConnectionPtr m_pConn(_uuidof(Connection)); //定义ADO连接
m_pCon.CreateInstance(__uuidof(Connection));
_CommandPtr m_pCmd(_uuidof(Command));
_RecordsetPtr m_pRst(_uuidof(Recordset)); //记录集
m_pRst.CreateInstance("ADODB.Recordset");
//对应释放与关闭
pRst->Close();1.操作Access数据库:
1.1 连接数据库连接串:_bstr_t strConnect ="uid=;pwd=;DRIVER={Microsoft Access Driver (*.mdb)};DBQ=Info1.mdb";//DBQ:数据库名称
连接数据库对象:m_pConn->Open(strConnect,"","",adConnectUnspecified);
1.2 查询语句:m_pRst->Open("select * from Info1",_variant_t((IDispatch *)m_pConn),adOpenStatic,adLockOptimistic,adCmdText);
1.3 增加语句:m_pRst->AddNew(); m_pRst->PutCollect("ID",_variant_t("322720"));
1.4 删除语句:m_pRst->MoveFirst();
m_pRst->Delete(adAffectCurrent);
m_pRst->Update();
1.5 修改语句:m_pRst->Move(1,_variant_t((long)adBookmarkFirst));
m_pRst->put_Collect(_variant_t("ID"),_variant_t("322700"));
m_pRst->Update();
2. 操作SQL Server
2.1 连接字符串:1).strSqlCmd.Format(_T("Provider = SQLOLEDB.1;Persist Security Info = true;User ID = %s;Password=%s;\
Initial Catalog = %s;Data Source = %s"),_T("sa"),_T("1231213"),strServ,strSqlSource);//Initial Catalog:数据库名称 Data Source:服务器名称
2).strConnect="Driver={SQL Server};Server=127.0.0.0\abc;Database=abc"; //Server:服务器名称;Database:数据库名称
连接数据库对象:m_pCon->Open(_bstr_t(strConnect),_bstr_t(UserID),_bstr_t(PassWord),-1);
2.2 打开数据表:m_pRst->Open("select * from Info2",_variant_t((IDispatch*)m_pConn),adOpenStatic,adLockOptimistic,adCmdText);
2.3 获取信息:m_pRst->GetCollect("name"); / m_pRst->GetCollect((long)0);
2.4 插入、删除、修改:m_pConn->Execute((_bstr_t)strTemp,&RecordsAffected,adCmdText); // strTemp:为数据库操作语句