关于ADO访问SQL数据库的问题。
请看下面这段代码:
void CTestDlg::OnConnect()
{
strcpy(g_dbinfo.str_dbip,"192.168.1.253");
strcpy(g_dbinfo.str_DBNAME,"zjk");
strcpy(g_dbinfo.str_DBUSER,"sa");
strcpy(g_dbinfo.str_DBPASS,"sa");
DisConnectDB(g_pConRecv);
variant_t vRowaffected;
CString strsql;
strsql.Format("select * from worker");
_bstr_t b_sql=_bstr_t(strsql);
try
{g_pConRecv->BeginTrans();
g_pConRecv->Execute(b_sql,&vRowaffected,adCmdText);
g_pConRecv->CommitTrans();
MessageBox("Update Successfully!");
}
catch(_com_error err)
{CString str;
str.Format("错误信息是%s",err.ErrorMessage());
str.Format("错误描述是%s",(char *)err.Description());
DisConnectDB(g_pConRecv);
ConnectDB(g_dbinfo,g_pConRecv);
::AfxMessageBox("ExeCute TS Error 01!"); }
}
BOOL ConnectDB(DBINFO dbinfo,_ConnectionPtr& pCon)
{
HRESULT hr;
hr= pCon.CreateInstance(__uuidof(Connection));
if(FAILED(hr))
{
return FALSE;
}
CString temp="";
temp.Format("Provider=SQLOLEDB;Persist Security Info=False;Initial Catalog=%s;Server=%s;Auto Translate=False",dbinfo.str_DBNAME,dbinfo.str_dbip);
try
{
pCon->Open(_bstr_t(temp),_bstr_t(dbinfo.str_DBUSER),_bstr_t(dbinfo.str_DBPASS), -1);
}
catch(_com_error err)
{
::AfxMessageBox("Connect error.");
CString str;
str="连接数据库失败";
str.Format("错误信息是%s",err.ErrorMessage());
str.Format("错误描述是%s",(char *)err.Description());
return FALSE;
}
catch(...)
{
return FALSE;
}
return TRUE;
}
void DisConnectDB(_ConnectionPtr& pCon)
{
if(pCon!=NULL)
{pCon.Release();
pCon=NULL;
}
return;
}
编译没有错误,但是执行时却报告g_pConRecv指针无效,我觉得该指针没有被正确的负值,但是在另一个程序中这样用就可以正常运行,请问怎样给g_pConRecv指针负值?