//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;
}