|
- /// <summary>
- /// 读取MDB
- /// </summary>
- /// <param name="mdbMpPath">MDB路径</param>
- /// <param name="strSql">sql语句</param>
- /// <param name="zddz"></param>
- void CMyPalette1ChildDlg::ReadMDB(const CString& mdbMpPath, const CString& strSql, std::map<CString, CString>& zddz)
- {
- if (!AfxOleInit())//这就是初始化COM库
- {
- AfxMessageBox(L"OLE初始化出错!");
- return;
- }
- _ConnectionPtr m_pConnection;
-
- _RecordsetPtr m_pRecordset;
-
- //_CommandPtr m_pCommand;
-
- CString strSQL; //配置初始连接串
- strSQL = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=";
- strSQL += mdbMpPath;
- strSQL += ";";
- HRESULT hr;
- try
- {
- hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象
- if (SUCCEEDED(hr))
- {
- hr = m_pConnection->Open((_bstr_t)strSQL, "", "", adModeUnknown);///连接数据库
- ///上面一句中连接字串中的Provider是针对ACCESS2000环境的,对于ACCESS97,需要改为:Provider=Microsoft.Jet.OLEDB.3.51; }
- m_pRecordset.CreateInstance("ADODB.Recordset");
- try
- {
- //打开数据库
- m_pRecordset->Open((_bstr_t)strSql,
- m_pConnection.GetInterfacePtr(),//或使用_variant_t((IDispatch*)theApp.m_pConnection,true),,但需要extern声明theApp;
- adOpenDynamic,
- adLockOptimistic,
- adCmdText);
- //遍历读取
-
- while (!m_pRecordset->adoEOF)//adoEOF判断数据库指针是否已经到结果集末尾;BOF判断是否在第一条记录前面
- {
- auto key = m_pRecordset->GetCollect("类型");
- //这里已经读到当前记录的ID,需要进行非空等判断,非空之后就可以处理,比如添加到列表框等。
- auto value = m_pRecordset->GetCollect("值");
- zddz[key] = value;
- //....
- m_pRecordset->MoveNext();
- }
-
- m_pRecordset->Close();//关闭记录集
- //m_pRecordset->Release();
- }
- catch (_com_error error)
- {
- if (m_pRecordset->State) {
- m_pRecordset->Close();//关闭记录集
- //m_pRecordset->Release();
- }
- CString errorMessage;
- errorMessage.Format(L"%s", (LPTSTR)error.Description());
- AfxMessageBox(errorMessage);
- return;
- }
- if (m_pConnection->State)//如果连接有效
- {
- m_pConnection->Close();
- //m_pConnection->Release();
- }
- }
- }
- catch (_com_error e)///捕捉异常
- {
- if (m_pRecordset->State) {
- m_pRecordset->Close();//关闭记录集
- //m_pRecordset->Release();
- }
- if (m_pConnection->State)//如果连接有效
- {
- m_pConnection->Close();
- //m_pConnection->Release();
- }
- CString errormessage;
- errormessage.Format(L"连接数据库失败!\r\n错误:%s!", e.ErrorMessage());
- AfxMessageBox(errormessage);///显示错误信息
- }
- }
复制代码 |
|