C++ 读取MDB数据库

/// <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);///显示错误信息
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值