连接数据库BOOL CLogin::ConnectDB(void)
{
HRESULT hr = NULL;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");///创建 Connection 对象
if(SUCCEEDED(hr))
{
//登录数据库并连接数据库DBCourse
//这里的server不能写成127.0.0.1否则会出现未指定的错误,应该写成Sql server登录界面的服务器名称
m_pConnection->ConnectionString = "driver={SQL Server};server=LOGO-PC\LOGO;uid=DBCourse;pwd=DBCourse;";
m_pConnection->Open("","","",adConnectUnspecified);
m_pConnection->DefaultDatabase = "DBCourse";
}
else
{
AfxMessageBox(TEXT("创建 Connection 对象失败"));///显示错误信息
return FALSE;
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format( TEXT("连接数据库失败 !\r\n 错误信息 :%s(%ld)"),e.ErrorMessage(),e.Error() );
AfxMessageBox(errormessage);///显示错误信息
return FALSE;
}
return TRUE;
}BO