代码如下
::CoInitialize(NULL);
try
{
// 创建Connection对象
m_pConnection.CreateInstance("ADODB.Connection");
// 设置连接字符串,必须是BSTR型或者_bstr_t类型
_bstr_t strConnect= "Provider=SQLOLEDB.1;Password=sa;Persist Security Info=True;User ID=sa;Initial Catalog=UserMan;Data Source=localhost;";
// m_pConnection->ConnectionTimeout=10;
m_pConnection->Open(strConnect,"","",adModeUnknown);
// 判断连接状态是否为连接
if(m_pConnection->State == adStateOpen)
MessageBox("连接数据库");
// 关闭连接
m_pConnection->Close();
// 判断连接状态是否为关闭
if(m_pConnection->State == adStateClosed)
MessageBox("断开连接");
}
// 捕捉异常
catch(_com_error e)
{
// 显示错误信息
AfxMessageBox(e.ErrorMessage());
}跳出未指定的错误异常
::CoInitialize(NULL);
try
{
// 创建Connection对象
m_pConnection.CreateInstance("ADODB.Connection");
// 设置连接字符串,必须是BSTR型或者_bstr_t类型
_bstr_t strConnect= "Provider=SQLOLEDB.1;Password=sa;Persist Security Info=True;User ID=sa;Initial Catalog=UserMan;Data Source=localhost;";
// m_pConnection->ConnectionTimeout=10;
m_pConnection->Open(strConnect,"","",adModeUnknown);
// 判断连接状态是否为连接
if(m_pConnection->State == adStateOpen)
MessageBox("连接数据库");
// 关闭连接
m_pConnection->Close();
// 判断连接状态是否为关闭
if(m_pConnection->State == adStateClosed)
MessageBox("断开连接");
}
// 捕捉异常
catch(_com_error e)
{
// 显示错误信息
AfxMessageBox(e.ErrorMessage());
}跳出未指定的错误异常
// 判断连接状态是否为关闭
if(m_pConnection->State == adStateClosed)
MessageBox("断开连接");
----------------------------------------m_pConnection已经被关闭了,就不能再判断它的状态了。
m_pConnection->Open(strConnect,"","",adModeUnknown);
{
if (m_strService.IsEmpty())
{
::MessageBox(NULL,"·þÎñÃû²»ÄÜΪ¿Õ","Ìáʾ",MB_OK);
return FALSE;
}
if (m_strDatabase.IsEmpty())
{
::MessageBox(NULL,"Êý¾Ý¿â²»ÄÜΪ¿Õ","Ìáʾ",MB_OK);
return FALSE;
} theApp.m_pConnection.CreateInstance(__uuidof(Connection));
try
{
theApp.m_strDatabase=m_strDatabase; CString strConn;
strConn="Provider=SQLOLEDB.1;Password=";
strConn+=m_strPassword;
strConn+=";Persist Security Info=True;User ID=";
strConn+=m_strUsername;
strConn+=";Initial Catalog=";
strConn+=m_strDatabase;
strConn+=";Data Source=";
strConn+=m_strService;
theApp.m_pConnection->Open((_bstr_t)strConn,
"",
"",
adModeUnknown);
}
catch(_com_error e)
{
::MessageBox(NULL,e.Description(),"Ìáʾ",MB_OK);
return FALSE;
}
::MessageBox(NULL,"Êý¾Ý¿âÁ¬½Ó³É¹¦£¡","Ìáʾ",MB_OK);
return TRUE;}看看跟上面程序有什么不同的地方。
_bstr_t strConnect= "Provider=SQLOLEDB; Server=127.0.0.1;Database=UserMan; uid=sa; pwd=sa;";
就可以了,什么原因