ADO_VARIABLE_LENGTH_BINDING
_ENTRY2的参数说明如下:
参数1:按顺序的字段号码,1为标识记录集中第一字段,2为标识记录集中第二字段,依此类推。
参数2:储存已转换字段的变量的数据类型。
参数3:临时的工作缓冲区,用于将字段值从 VARIANT转换为C/C++(www.cppentry.com) 变量。
参数4:变长变量所需的字节数。
参数5:指示字段转换是否成功。
参数6:布尔标志。如果为 TRUE,则表明 ADO 可以更新绑定的字段。如只检查字段而不将其更改,可设置为 FALSE。
其中第5个参数为状态参数,它可告诉你从 Recordset 字段到C或C++(www.cppentry.com)变量的转换是否成功以及变量的内容是否有效。该参数的两个最重要的值是adFldOK(意味着转换成功)和adFldNull(意味着字段是NULL,即无值可供转换)。程序中要检测该参数以决定C或C++(www.cppentry.com)变量是否有效。例如,如果字段具有有效的行内容,状态将会是adFldOK,如果移动到另一个字段为 NULL 的行,则状态将是 adFldNull。
源程序代码如下:
#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")
#include 〈stdio.h〉
#include 〈ole2.h〉
#include "ADOtest.h"
void main()
{
if(FAILED(::CoInitialize(NULL)))
return;
// 定义ADO 智能指针类的实例,并初始化
RecordsetPtr pRstAuthors = NULL;
//定义其它变量
//接口指针声明
IADORecordBinding picRs = NULL; CAuthorsRs authorsrs;
//ADO函数要返回HRESULT,宏代码可以帮我们解释HRESULT的含义
HRESULT hr;
// 打开 位于nt_sqlserver服务器上的 pubs数据库中的 Authors 表
bstr_t strCnn("Provider=sqloledb;Data Source=nt_sqlserver;"
"Initial Catalog=pubs;User Id=sa;Password=;");
try
{
// 从 Authors 表中打开记录集
if FAILED(hr = pRstAuthors.CreateInstance(__uuidof(Recordset)))
com_issue_error(hr);
pRstAuthors-〉CursorType = adOpenStatic;
// 使用 client 游标 ,从而可以使用 AbsolutePosition 属性pRstAuthors-〉CursorLocation = adUseClient;
pRstAuthors-〉Open("SELECT au_fname, au_lname, city, "
"state FROM Authors ORDER BY au_id", strCnn, adOpenStatic,
adLockReadOnly, adCmdText);
// 打开一个 IADORecordBinding 接口指针(用来对记录集和C++(www.cppentry.com)类的绑定)
if FAILED(hr = pRstAuthors-〉QueryInterface(_uuidof(IADORecordBinding),(LPVOID )&&picRs))
_com_issue_error(hr);
// 调用 BindToRecordset 接口方法可使 Recordset 字段关联(或绑定)到C/C++(www.cppentry.com) 变量,无论何时更改 Recordset 对象的当前行,C/C++(www.cppentry.com) 变量都将自动更新
if FAILED(hr = picRs-〉BindToRecordset(&&authorsrs))
_com_issue_error(hr);
pRstAuthors-〉MoveFirst();
while(true)
{
// 显示当前记录的信息
printf("Record %ld of %d\n", pRstAuthors-〉AbsolutePosition, pRstAuthors-〉RecordCount);
printf("Author: %s %s\n ",
authorsrs.l_fnameStatus == adFldOK
authorsrs.m_au_fname : "〈NULL〉",
authorsrs.l_lnameStatus == adFldOK
authorsrs.m_au_lname : "〈NULL〉");
printf("Location: %s, %s\n",
authorsrs.l_cityStatus == adFldOK
authorsrs.m_au_city : "〈NULL〉",
authorsrs.l_stateStatus == adFldOK
authorsrs.m_au_state : "〈NULL〉");
pRstAuthors-〉MoveNext();
if(pRstAuthors-〉EndOfFile)
{
break;
}
}
// 退出前释放对象
pRstAuthors-〉Close();
// 这里释放 IADORecordset 接口
if (picRs)
picRs-〉Release();
}
catch(_com_error &&e)
{
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}
::CoUninitialize();
} |
编译链接之后,程序就可以运行了。这个例子的作用是将SQL SERVER中pubs库中authors表中的记录按字段au_id排序后,将记录在记录集中的位置、姓名、城市等几个字段的内容依次显示在屏幕上。
|