提取数据
打开数据源、会话和行集对象后,可以提取数据。 根据所使用的访问器类型,可能需要绑定列。
提取数据
使用相应的 Open 命令打开行集。
如果使用
CManualAccessor
,请绑定输出列(如果尚未这样做)。 以下示例摘自 DBViewer 示例。 若要绑定列,请调用GetColumnInfo
,然后使用绑定创建访问器,如以下示例所示:// From the DBViewer Sample CDBTreeView::OnQueryEdit // Get the column information ULONG ulColumns = 0; DBCOLUMNINFO* pColumnInfo = NULL; LPOLESTR pStrings = NULL; if (rs.GetColumnInfo(&ulColumns, &pColumnInfo, &pStrings) != S_OK) ThrowMyOLEDBException(rs.m_pRowset, IID_IColumnsInfo); struct MYBIND* pBind = new MYBIND[ulColumns]; rs.CreateAccessor(ulColumns, &pBind[0], sizeof(MYBIND)*ulColumns); for (ULONG l=0; l<ulColumns; l++) rs.AddBindEntry(l+1, DBTYPE_STR, sizeof(TCHAR)*40, &pBind[l].szValue, NULL, &pBind[l].dwStatus); rs.Bind();
编写
while
循环以检索数据。 在循环中,调用MoveNext
前移游标并针对 S_OK 测试返回值,如以下示例所示:while (rs.MoveNext() == S_OK) { // Add code to fetch data here // If you are not using an auto accessor, call rs.GetData() }
在
while
循环中,可以根据访问器类型提取数据。如果使用 CAccessor 类,则应具有包含数据成员的用户记录。 可以使用这些数据成员访问数据,如以下示例所示:
while (rs.MoveNext() == S_OK) { // Use the data members directly. In this case, m_nFooID // is declared in a user record that derives from // CAccessor wsprintf_s("%d", rs.m_nFooID); }
如果使用
CDynamicAccessor
或CDynamicParameterAccessor
类,则可以使用访问函数GetValue
和GetColumn
来提取数据,如以下示例所示。 如果要确定所使用的数据类型,请使用GetType
。while (rs.MoveNext() == S_OK) { // Use the dynamic accessor functions to retrieve your data. ULONG ulColumns = rs.GetColumnCount(); for (ULONG i=0; i<ulColumns; i++) { rs.GetValue(i); } }
如果使用
CManualAccessor
,则必须指定自己的数据成员,自行绑定并直接访问它们,如以下示例所示:while (rs.MoveNext() == S_OK) { // Use the data members you specified in the calls to // AddBindEntry. wsprintf_s("%s", szFoo); }