1、如果返回的是多个结果集,DataReader 会提供 NextResult 方法来按顺序循环访问这些结果集,如以下代码示例所示。
SqlCommand myCMD = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;" +
"SELECT EmployeeID, LastName FROM Employees", nwindConn);
nwindConn.Open();
SqlDataReader myReader = myCMD.ExecuteReader();
do
{
Console.WriteLine("\t{0}\t{1}", myReader.GetName(0), myReader.GetName(1));
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
} while (myReader.NextResult());
myReader.Close();
nwindConn.Close();
2、从 DataReader 中获取架构信息
当 DataReader 打开时,可以使用 GetSchemaTable 方法检索有关当前结果集的架构信息。GetSchemaTable 将返回一个填充了行和列的 DataTable 对象,这些行和列包含当前结果集的架构信息。对于结果集的每一列,DataTable 都将包含一行。架构表行的每一列都映射到在结果集中返回的列的属性,其中 ColumnName 是属性的名称,而列的值为属性的值。以下代码示例为 DataReader 写出架构信息。
DataTable schemaTable = myReader.GetSchemaTable();
foreach (DataRow myRow in schemaTable.Rows)
{
foreach (DataColumn myCol in schemaTable.Columns)
Console.WriteLine(myCol.ColumnName + " = " + myRow[myCol]);
Console.WriteLine();
}
3、OLE DB 章节
分层行集或章节(OLE DB 类型 DBTYPE_HCHAPTER、ADO 类型 adChapter)可以使用 OleDbDataReader 来检索。当以 DataReader 的形式返回包含某章节的查询时,该章节将以此 DataReader 中列的形式返回,并公开为 DataReader 对象。
ADO.NET DataSet 也可用于通过表间的父子关系来表示分层行集。有关的更多信息,请参阅创建和使用 DataSet。
以下代码示例使用 MSDataShape 提供程序来为客户列表中的每个客户生成订单的章节列。
OleDbConnection nwindConn = new OleDbConnection("Provider=MSDataShape;Data Provider=SQLOLEDB;" +
"Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");
OleDbCommand custCMD = new OleDbCommand("SHAPE {SELECT CustomerID, CompanyName FROM Customers} " +
" APPEND ({SELECT CustomerID, OrderID FROM Orders} AS CustomerOrders " +
" RELATE CustomerID TO CustomerID)", nwindConn);
nwindConn.Open();
OleDbDataReader custReader = custCMD.ExecuteReader();
OleDbDataReader orderReader;
while (custReader.Read())
{
Console.WriteLine("Orders for " + custReader.GetString(1));
// custReader.GetString(1) = CompanyName
orderReader = (OleDbDataReader)custReader.GetValue(2);
// custReader.GetValue(2) = Orders chapter as DataReader
while (orderReader.Read())
Console.WriteLine("\t" + orderReader.GetInt32(1));
// orderReader.GetInt32(1) = OrderID
orderReader.Close();
}
custReader.Close();
nwindConn.Close();