5. DBRecordSetImpl.h
#pragma once
typedef _RecordsetPtr CADORecordSetPtr;
class CDBRecordSetImpl
{
//构造函数和析构函数
public:
CDBRecordSetImpl(void);
virtual ~CDBRecordSetImpl(void);
//copy constructor
CDBRecordSetImpl(const CDBRecordSetImpl& rRecordSetImpl) ;
//operator = ,如果复制成功,则GetErrorMessage()返回空串
CDBRecordSetImpl& operator= (const CDBRecordSetImpl& rRecordSetImpl) ;
//接口函数
public:
//返回记录集
CADORecordSetPtr& GetRecordSet(void);
/*
* 判断当前记录集是否已经创建对象
*/
BOOL isValid(void) ;
void SetErrorMessage(LPCTSTR szErrMsg,const char* szSourceFile=NULL,int nLine=0) ;
const CString& GetErrorMessage(void) ;
protected:
//记录集
CADORecordSetPtr m_pRecordSetPtr;
//error message
CString m_strErrMsg ;
};
inline CADORecordSetPtr& CDBRecordSetImpl::GetRecordSet(void)
{
return m_pRecordSetPtr ;
}
inline BOOL CDBRecordSetImpl::isValid(void)
{
return (m_pRecordSetPtr != NULL) ;
};
inline const CString& CDBRecordSetImpl::GetErrorMessage(void)
{
return m_strErrMsg;
}
6.DBRecordSetImpl.cpp
#include "StdAfx.h"
#include "dbrecordsetimpl.h"
#include "DBErrorMsgDefs.h"
CDBRecordSetImpl::CDBRecordSetImpl(void)
{
try
{
m_pRecordSetPtr.CreateInstance(__uuidof(Recordset));
}
catch (_com_error &e)
{
SetErrorMessage((LPCTSTR)e.Description(),__FILE__,__LINE__) ;
}
catch (...)
{
SetErrorMessage(EXCEPTION_UNKNOWN,__FILE__,__LINE__) ;
}
}
CDBRecordSetImpl::~CDBRecordSetImpl(void)
{
try
{
//关闭连接,并释放对象
if (m_pRecordSetPtr != NULL)
{
if(m_pRecordSetPtr->GetState() != adStateClosed)
{
m_pRecordSetPtr->Close() ;
}
m_pRecordSetPtr = NULL ;
}
}
catch (_com_error &e)
{
SetErrorMessage((LPCTSTR)e.Description(),__FILE__,__LINE__) ;
}
catch (...)
{
SetErrorMessage(EXCEPTION_UNKNOWN,__FILE__,__LINE__) ;
}
}
//copy constructor
CDBRecordSetImpl::CDBRecordSetImpl(const CDBRecordSetImpl& rRecordSetImpl):
m_pRecordSetPtr(NULL)
{
*this = rRecordSetImpl ;
}
//operator =
CDBRecordSetImpl& CDBRecordSetImpl::operator= (const CDBRecordSetImpl& rRecordSetImpl)
{
if(this == &rRecordSetImpl)
{
return *this ;
}
//错误信息不复制,如果复制成功,则m_strErrMsg为空
try
{
m_strErrMsg = _T("");
//clone it from destination
if(rRecordSetImpl.m_pRecordSetPtr != NULL)
{
if(rRecordSetImpl.m_pRecordSetPtr->GetState() == adStateOpen)
{
//关闭连接,并释放对象
if (m_pRecordSetPtr != NULL)
{
if(m_pRecordSetPtr->GetState() != adStateClosed)
{
m_pRecordSetPtr->Close() ;
}
m_pRecordSetPtr = NULL ;
}
m_pRecordSetPtr = rRecordSetImpl.m_pRecordSetPtr->Clone(adLockUnspecified) ;
}
}
}
catch (_com_error &e)
{
SetErrorMessage((LPCTSTR)e.Description(),__FILE__,__LINE__) ;
}
catch (...)
{
SetErrorMessage(EXCEPTION_UNKNOWN,__FILE__,__LINE__) ;
}
return *this ;
}
void CDBRecordSetImpl::SetErrorMessage(LPCTSTR szErrMsg,const char* szSourceFile,int nLine)
{
m_strErrMsg = szErrMsg ;
}