先给出工具类的定义
class CAdoUtil
{
public:
BOOL ConnectDB();
BOOL DisConnectDB();
BOOL ConnectDB(CString &szServer,CString &szName,CString &szPassword);
_ConnectionPtr GetConnectionPtr();
CAdoUtil();
virtual ~CAdoUtil();
private:
_ConnectionPtr m_pconnection;
};
无参连接函数
BOOL CAdoUtil::ConnectDB()
{
CString szServer ="127.0.0.1";
CString szname ="Runner";
CString szpassword ="123456";
try
{
if(ConnectDB(szServer,szname,szpassword) ==FALSE)
{
return false;
}
}
catch(_com_error e)
{
throw e;
}
return true;
}
含参连接函数
BOOL CAdoUtil::ConnectDB(CString &szServer, CString &szName, CString &szPassword)
{
if(m_pconnection!=NULL)
return FALSE;
CString szconnect ="";
szconnect.Format(_T("Provider=SQLOLEDB.1;Server=%s;DataBase=Warehouse_managemen_system;User ID=%s;Password=%s;"),szServer,szName,szPassword);
try
{
HRESULT hr =m_pconnection.CreateInstance(__uuidof(Connection));
if(FAILED(hr))
{ AfxMessageBox("程序异常1");
return FALSE;
}
if(FAILED(m_pconnection->Open((_bstr_t)szconnect,_T(""),_T(""),adModeUnknown))) //__用断点调试发现是这里除了异常,为E_FAIL
{ // AfxMessageBox("程序异常2");
m_pconnection.Release();
return FALSE;
}
}
catch(_com_error e)
{
if(m_pconnection!=NULL &&m_pconnection->GetState()!= adStateClosed)
{
m_pconnection->Close();
m_pconnection.Release();
m_pconnection =NULL;
}
throw e;
}
catch(...)
{
AfxMessageBox("程序异常A");
}
return true;
}
数据库通过Server身份验证方式登陆,用了自己创建的用户Runner,表有如下配置
本人学生,没系统学过数据库和ADO,还望各位多多包涵~