[问题] 一个ADO在C++里头的问题

苦逼热狗

路边通讯社社长
VIP
注册
2002-10-12
消息
47,114
荣誉分数
2,376
声望点数
393
第一次用ADO,有不少不懂得地方,希望大家帮忙
Q1:
HRESULT ExecuteSQL(const wchar_t* szUnicodeString)
{
HRESULT hr;
hr = recordset->Open(szUnicodeString,
connection.GetInterfacePtr(),
ADODB::adOpenForwardOnly,
ADODB::adLockReadOnly,
ADODB::adCmdText);
return hr;
}

wchar_t* pStatement;
pStatement = L"select * from userdata WHERE userid = 1";

if (ExecuteSQL(pStatement) == S_OK)
printf("select successuful\n");
else
printf("select failed\n");

我想知道能否在每次调用这个ExecuteSQL结束的时候
都清理一下recordset呢?
有啥函数可以调用呢

或者我需要每一次调用都生成一个instance,然后使用结束以后再摧毁掉

代码:
HRESULT ExecuteSQL(const wchar_t* szUnicodeString)
{
ADODB::_RecordsetPtr recordset;
HRESULT hr;
recordset.CreateInstance(__uuidof(ADODB::Recordset));
hr = recordset->Open(szUnicodeString,
					connection.GetInterfacePtr(), 
					ADODB::adOpenForwardOnly,
					ADODB::adLockReadOnly, 
					ADODB::adCmdText);

.........
//do something with the selected data from SQL
.........

recordset->Close();
recordset->Release();
recordset = NULL;
return hr;
}
ADO1.5 / VC++6.0
 
习惯上资源使用完后应该里立即释放,第二种做法是正确的。如果你的确需要将Recordset返回给调用者,最好Connection使用client游标,或者动态在内存创建一个跟原来结构一样的disconnected recordset,然后将需要的数据拷贝进去,然后释放原来的recordset。
 
我觉得我这么写会简单点,因为对ADO不熟悉

然后在只是简单update/insert一类的query时候,用之前第二种方法

代码:
HRESULT ExecuteSQL(const wchar_t* szUnicodeString, LPUSERDATA lpua)
{

ADODB::_RecordsetPtr recordset;
HRESULT hr;
_variant_t var;

RtlZeroMemory(lpua, sizeof(USERDATA));
recordset.CreateInstance(__uuidof(ADODB::Recordset));
hr = recordset->Open(szUnicodeString,
					connection.GetInterfacePtr(), 
					ADODB::adOpenForwardOnly,
					ADODB::adLockReadOnly, 
					ADODB::adCmdText);

var = recordset->Fields->GetItem(L"userid")->GetValue();
lpua->userid = var.intVal;
....
something like this
....


recordset->Close();
recordset->Release();
recordset = NULL;
return hr;
}
 
There is one place you may need to know that _RecordsetPtr is defined as something like _com_ptr<_Recordset>, which is actually a wrapper around ADO native interface using smart pointer, and its wrapper functions will throw exception in case of SQL error, and your "return hr" will never be executed.
 
okie, thanks for telling me that
i will use an additional try and catch to get the exception is anything goes wrong.
 
后退
顶部