| #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++类的绑定) if FAILED(hr = pRstAuthors-〉QueryInterface(_uuidof(IADORecordBinding),(LPVOID)&&picRs)) _com_issue_error(hr); // 调用 BindToRecordset 接口方法可使 Recordset 字段关联(或绑定)到C/C++ 变量,无论何时更改 Recordset 对象的当前行,C/C++ 变量都将自动更新 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(); } |