Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Разработка приложений баз данных (Visual Studio 2008).docx
Скачиваний:
143
Добавлен:
26.03.2016
Размер:
1.01 Mб
Скачать

Создание DataReader(ado.Net)

Классы DataTableиDataSetимеют методCreateDataReader, возвращающий содержимое объектаDataTableили содержимое объектаDataSetколлекцииTablesв виде одного или нескольких доступных для чтения результирующих наборов с последовательным доступом.

Пример

Следующее приложение командной строки создает экземпляр DataTable. Затем в этом примере передается заполненный объектDataTableв процедуру, вызывающую методCreateDataReader, который выполняет итерацию по результатам, содержащимся в объектеDataTableReader.

Язык C#

private static void TestCreateDataReader(DataTable dt)

{

// Given a DataTable, retrieve a DataTableReader

// allowing access to all the tables' data:

using (DataTableReader reader = dt.CreateDataReader())

{

do

{

if (!reader.HasRows)

{

Console.WriteLine("Empty DataTableReader");

}

else

{

PrintColumns(reader);

}

Console.WriteLine("========================");

} while (reader.NextResult());

}

}

private static DataTable GetCustomers()

{

// Create sample Customers table, in order

// to demonstrate the behavior of the DataTableReader.

DataTable table = new DataTable();

// Create two columns, ID and Name.

DataColumn idColumn = table.Columns.Add("ID", typeof(int));

table.Columns.Add("Name", typeof(string));

// Set the ID column as the primary key column.

table.PrimaryKey = new DataColumn[] { idColumn };

table.Rows.Add(new object[] { 1, "Mary" });

table.Rows.Add(new object[] { 2, "Andy" });

table.Rows.Add(new object[] { 3, "Peter" });

table.Rows.Add(new object[] { 4, "Russ" });

return table;

}

private static void PrintColumns(DataTableReader reader)

{

// Loop through all the rows in the DataTableReader

while (reader.Read())

{

for (int i = 0; i < reader.FieldCount; i++)

{

Console.Write(reader[i] + " ");

}

Console.WriteLine();

}

}

В этом примере отображаются следующие выходные данные в окне консоли:

1 Mary

2 Andy

3 Peter

4 Russ

Навигация в объектах DataTableReader

В следующем примере метод TestConstructor создает два экземпляра DataTable. Чтобы продемонстрировать работу конструктора для классаDataTableReader, данный образец создает новый объектDataTableReaderна основе массива, содержащего две таблицыDataTables, и выполняет простую операцию, выводя содержимое первых столбцов в окно консоли.

Язык C#

private static void TestConstructor()

{

// Create two data adapters, one for each of the two

// DataTables to be filled.

DataTable customerDataTable = GetCustomers();

DataTable productDataTable = GetProducts();

// Create the new DataTableReader.

using (DataTableReader reader = new DataTableReader(

new DataTable[] { customerDataTable, productDataTable }))

{

// Print the contents of each of the result sets.

do

{

PrintColumns(reader);

} while (reader.NextResult());

}

Console.WriteLine("Press Enter to finish.");

Console.ReadLine();

}

private static DataTable GetCustomers()

{

// Create sample Customers table, in order

// to demonstrate the behavior of the DataTableReader.

DataTable table = new DataTable();

// Create two columns, ID and Name.

DataColumn idColumn = table.Columns.Add("ID", typeof(int));

table.Columns.Add("Name", typeof(string ));

// Set the ID column as the primary key column.

table.PrimaryKey = new DataColumn[] { idColumn };

table.Rows.Add(new object[] { 1, "Mary" });

table.Rows.Add(new object[] { 2, "Andy" });

table.Rows.Add(new object[] { 3, "Peter" });

table.Rows.Add(new object[] { 4, "Russ" });

return table;

}

private static DataTable GetProducts()

{

// Create sample Products table, in order

// to demonstrate the behavior of the DataTableReader.

DataTable table = new DataTable();

// Create two columns, ID and Name.

DataColumn idColumn = table.Columns.Add("ID", typeof(int));

table.Columns.Add("Name", typeof(string ));

// Set the ID column as the primary key column.

table.PrimaryKey = new DataColumn[] { idColumn };

table.Rows.Add(new object[] { 1, "Wireless Network Card" });

table.Rows.Add(new object[] { 2, "Hard Drive" });

table.Rows.Add(new object[] { 3, "Monitor" });

table.Rows.Add(new object[] { 4, "CPU" });

return table;

}

private static void PrintColumns(DataTableReader reader)

{

// Loop through all the rows in the DataTableReader

while (reader.Read())

{

for (int i = 0; i < reader.FieldCount; i++)

{

Console.Write(reader[i] + " ");

}

Console.WriteLine();

}

}