VS下ADO数据库连接

//ADO//数据库连接
①加载\#import “C:\program files\common files\system\ado\msado15.dll” no_namespace rename (“EOF”, “adoEOF”)\dll文件.
②CoInitialize(NULL);初始化COM库
③连接
④CoUninitialize();//卸载ADO COM库
下面为连接封装的函数。。。。
int connect_db(CString &sqlname,CString &m_strbrowsetct)
{

HRESULT hr;

///
if(sqlname == L"SQL")
{
	//hr = m_rea.CreateInstance(_uuidof(Recordset));//
	//if(FAILED(hr))
	//{
	//	AfxMessageBox(L"m_ree CreateInstance failed....");
	//	return -1;
	//}
	_bstr_t strConnecta= _T("Provider=SQLOLEDB.1;Data Source=csj-od-sql16;Initial Catalog=AutoDashboardDB;User ID=Automation;PWD=AutoDashboardDB#001");
	try
	{
			hr = m_coa.CreateInstance(_uuidof(Connection));//实例化m_co对象、COM技术ADODB.Connection
			if(SUCCEEDED(hr))//实例化是否成功
			{
			
				m_coa->ConnectionTimeout = 20;//设置连接超时时间
					hr = m_coa->Open(_bstr_t( LPCTSTR(strConnecta)),"","",/*adConnectUnspecified*/adModeUnknown);//同步连接数据库
					if(SUCCEEDED(hr))
					{
						AfxMessageBox(L"m_coe and m_coa all connect success....");
						return 0 ;
					}
					else
					{
		
						AfxMessageBox(L"m_coe connect failed....");
						return -1 ;
					}
		
			}

	}	
	catch (_com_error &e)//错误捕获
	{
		_bstr_t bstrSouce(e.Source());
		_bstr_t bstrDescription(e.Description());
		AfxMessageBox(bstrDescription+bstrSouce);
		return -1;
	}
	m_rea = NULL;
}
//
else
{
	//hr = m_ree.CreateInstance(_uuidof(Recordset));//
	//if(FAILED(hr))
	//{
	//	AfxMessageBox(L"m_ree CreateInstance failed....");
	//	return -1;
	//}
	/*_bstr_t strConnecte = _T("Provider=SQLOLEDB.1;Data Source=csj-od-sql16;Initial Catalog=AutoDashboardDB;User ID=Automation;PWD=AutoDashboardDB#001");
	*/
	/*_bstr_t strConnecte = _T("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=");
	strConnecte += _bstr_t (m_strbrowsetct);
	strConnecte += _T(";Persist Security Info=False;");*/
	_bstr_t strConnecte= _T("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=");
	strConnecte += _bstr_t (m_strbrowsetct);
	strConnecte += _T(";Extended Properties=\"Excel 12.0;HDR=YES;\"");
	try
	{
			hr = m_coe.CreateInstance(_uuidof(Connection));//实例化m_co对象、COM技术ADODB.Connection
			if(SUCCEEDED(hr))//实例化是否成功
			{
			
				m_coe->ConnectionTimeout = 20;//设置连接超时时间
					hr = m_coe->Open(_bstr_t( LPCTSTR(strConnecte)),"","",adConnectUnspecified);//同步连接数据库
					if(SUCCEEDED(hr))
					{
						AfxMessageBox(L"m_coe and m_coa all connect success....");
						return 0 ;
					}
					else
					{
		
						AfxMessageBox(L"m_coe connect failed....");
						return -1 ;
					}
		
			}

	}	
	catch (_com_error &e)//错误捕获
	{
		_bstr_t bstrSouce(e.Source());
		_bstr_t bstrDescription(e.Description());
		AfxMessageBox(bstrDescription+bstrSouce);
		return -1;
	}
	m_ree = NULL;
}
return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值