Ado操作数据库,关闭记录集的时候发生错误。(代码很短)

稀饭桶子 发布于 2013/08/24 16:45
阅读 540
收藏 0
//建立连接
	_ConnectionPtr pConn;
	_RecordsetPtr pRs("ADODB.Recordset");
	CString strSQL="Driver=MySQL ODBC 5.1 Driver; SERVER=localhost; DATABASE=test; UID=root; PASSWORD=123456;OPTION=3;";
	pConn.CreateInstance(__uuidof(Connection));
	pConn->CursorLocation=adUseClient;
	pConn->Open(_bstr_t(strSQL),"","",-1);


	//查询记录并输出
	pRs->Open("Select * From test",_variant_t(pConn,true),adOpenStatic,adLockOptimistic,adCmdText);
	AllocConsole();  
	freopen( "CONOUT$", "w+t", stdout );// 申请写
	freopen( "CONIN$", "r+t", stdin );  // 申请读

	char szCh[21];
	while(!pRs->GetadoEOF())
	{
		_variant_t varId = pRs->GetCollect("id");
		_variant_t varName = pRs->GetCollect("name");
		WideCharToMultiByte 
             (CP_ACP, 0, varName.bstrVal, -1,
              szCh, sizeof(szCh), NULL, NULL);
		cout<<varId.intVal<<szCh<<endl;
		pRs->MoveNext();
	}
	system("pause");
	FreeConsole();

	
	pConn->Close();
	//关闭记录集的时候发生错误 
	pRs->Close();
加载中
0
redzl
redzl
rs是要用到conn的,所以你关闭的顺序应该是先关闭rs再关闭conn吧
0
稀饭桶子
稀饭桶子

引用来自“redzl”的答案

rs是要用到conn的,所以你关闭的顺序应该是先关闭rs再关闭conn吧
感谢帮助,已解决
0
稀饭桶子
稀饭桶子

引用来自“redzl”的答案

rs是要用到conn的,所以你关闭的顺序应该是先关闭rs再关闭conn吧

还能问一个问题吗?插入记录的时候出错

//建立连接
	_ConnectionPtr pConn;
	_RecordsetPtr pRs("ADODB.Recordset");
	CString strSQL="Driver=MySQL ODBC 5.1 Driver; SERVER=localhost; DATABASE=test; UID=root; PASSWORD=123456;OPTION=3;";
	pConn.CreateInstance(__uuidof(Connection));
	pConn->CursorLocation=adUseClient;
	pConn->Open(_bstr_t(strSQL),"","",-1);

	pRs->AddNew();///这边有Unhandled Exception
	pRs->PutCollect("id",(_variant_t)((long)3));
	pRs->PutCollect("name",(_variant_t)("TT"));
	pRs->Update();
	//查询记录并输出
	pRs->Open("Select * From test",_variant_t(pConn,true),adOpenStatic,adLockOptimistic,adCmdText);
	
	AllocConsole();  
	freopen( "CONOUT$", "w+t", stdout );// 申请写
	freopen( "CONIN$", "r+t", stdin );  // 申请读

	char szCh[21];
	while(!pRs->GetadoEOF())
	{
		_variant_t varId = pRs->GetCollect("id");
		_variant_t varName = pRs->GetCollect("name");
		WideCharToMultiByte 
             (CP_ACP, 0, varName.bstrVal, -1,
              szCh, sizeof(szCh), NULL, NULL);
		cout<<varId.intVal<<szCh<<endl;
		pRs->MoveNext();
	}
	system("pause");
	FreeConsole();

	pRs->Close();
	pConn->Close();
	pRs=NULL;
	pConn=NULL;

0
redzl
redzl

根据我使用ASP的经验来说,你的AddNew上面要打开一次rs,并且将 adLockOptimistic这个参数位置的值设置为3(也就是adLockOptimistic常量),针对你的代码来说,你需要在AddNew上面加一句:

pRs->Open("Select * From test where id is null",_variant_t(pConn,true),adOpenStatic,adLockOptimistic,adCmdText);

而你下面的查询并输出,为了节省资源着想,第三个参数可以设置为1(也就是adLockReadOnly )

返回顶部
顶部