SQLSERVER数据库连接的配置及数据集的设置
HRESULT hr =S_FALSE;
_RecordsetPtr m_QryRcdSet;
_ConnectionPtr m_pConnection;
hr =m_pConnection.CreateInstance("ADODB.Connection");
if (FAILED(hr))
return FALSE;
try
{
m_pConnection->ConnectionTimeout =8;
CString strConnect = "Provider=SQLOLEDB.1;Data Source=" + (数据库服务器的IP) + ";Initial Catalog=" + (数据库的名称)+ ";User ID="
+ (用户名)+ "; PWD=" +(密码);
m_pConnection->Open(_bstr_t(strConnect),"","",adModeUnknown);
}
catch(_com_error e)///捕捉异常
{
AfxMessageBox("数据库连接失败!" +CString(e.ErrorMessage()));
ASSERT(FALSE);
return FALSE;
}
hr =m_QryRcdSet.CreateInstance("ADODB.Recordset");
if (FAILED(hr))
return FALSE;
try
{
m_QryRcdSet->CursorType =adOpenStatic;
m_QryRcdSet->CursorLocation =adUseClient;
hr = m_QryRcdSet->Open(_bstr_t(SqlStr),_variant_t((IDispatch *)m_pConnection, true), adOpenDynamic, adLockPessimistic, adCmdText);
ADO_LONGPTR count =m_QryRcdSet->GetRecordCount();
if(count > 0)
m_QryRcdSet->MoveFirst();
}
catch(_com_error e)///捕捉异常
{
e.Description();
AfxMessageBox(e.Description());
AfxMessageBox("数据库连接失败!" + CString(e.ErrorMessage()));
ASSERT(FALSE);
return FALSE;
}
在stdafx.h文件中加入以下语句:
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")