我的代码简写如下:
class CLogMngr
{
public:
CLogMngr();
virtual ~CLogMngr();
public:
void Setup(_ConnectionPtr cnnt, CString& user,long & Authority)
{
m_DBCnt = cnnt;
m_user = user;
m_Authority=Authority;
}
protected:
_ConnectionPtr m_DBCnt;
CString m_user;
long m_Authority;
};
CLogMngr::CLogMngr()
{
}CLogMngr::~CLogMngr()
{
}
class CSCHOOlApp : public CWinApp
{
public:
_ConnectionPtr m_DBCnt;
CLogMngr m_logMngr;
}
BOOL CSCHOOlApp::InitInstance()
{
try
{
m_DBCnt.CreateInstance(_uuidof(Connection));
CString sql_;
_RecordsetPtr pRst=NULL;
sql_.Format("DSN=SCHOOL;UID=anxing;PWD=234811");
_bstr_t sql=sql_;
VARIANT holder;
m_DBCnt->Open(sql,"","",-1);
sql_.Format("select * from table ");
sql=sql_;
pRst=m_DBCnt->Execute(sql,NULL,adCmdText);
pRst->Close();
}
catch(_com_error &e)
{
AfxMessageBox(e.ErrorMessage());
}
return TRUE;
};
int CSCHOOlApp::ExitInstance()
{
m_DBCnt->Close();
return CWinApp::ExitInstance();
}
在VIEW中我通过全局对象theApp来得到m_DBCnt
class CMYView : public CFormView
{
protected:
_ConnectionPtr m_DBCnt;
CLogMngr *m_logMngr;}
extern CSCHOOlApp theApp;
CMYView::CMYView()
{
m_DBCnt=theApp.m_DBCnt;
m_logMngr=&(theApp.m_logMngr);
}
如果应用程序打开后关闭(什么也不做)一切正常。但是当我对于VIEWF进行操作。如在VIEW中对数据库进行添加。结束时出现了引用非法内存。f5调试出现对话框Unhanded exception in anxing.exe
是在应用程序结束析构
CLogMngr::~CLogMngr(){}默认调用Release()时出现了错误。
请问:在哪里可能出现了错误?
{
m_DBCnt=NULL;
CoUninitialize(); //这里跟你在工程初始化时的调用匹配;
return CWinApp::ExitInstance();
}
不用关闭数据库?
thank you ~~~~
to : mahatma_cn(要打架吗?)
thank you ~~~
你们的方法都很好。mahatma_cn(要打架吗?) 说出了本质,以后我会这样做。对于这里,我才用
CharmDream() 的方法,呵呵,有点偷机,他会让系统认为已经删除了。
m_DBCnt = NULL;是一种有效而且比Close有效的方法,虽然我不敢100%肯定
请看m_DBCnt的声明
_ConnectionPtr m_DBCnt;
这个变量是一个指针
再看如下赋值操作
m_DBCnt=theApp.m_DBCnt;
这是指针赋值,传递的是地址
也就是说对m_DBCnt做的操作就是对theApp.m_DBCnt做的操作
m_DBCnt->Close 等价于 theApp.m_DBCnt->Close 设想:
m_DBCnt1=theApp.m_DBCnt;
m_DBCnt2=theApp.m_DBCnt;
……
m_DBCntn=theApp.m_DBCnt;
我斗胆妄言您把m_DBCnt设成全局变量就是要这样用
然而 如前所述任何一个m_DBCnti->Close 都等价于 theApp.m_DBCnt->Close
因为是“指针”,这恐怕不是您所希望的……末了,一句话:将指向连接对象的最后一个变量设置为NULL将隐含地关闭连接对象