Tải bản đầy đủ - 0 (trang)
9-12. Create an In-Memory Cache

9-12. Create an In-Memory Cache

Tải bản đầy đủ - 0trang

CHAPTER 9 ■ DATABASE ACCESS



when you call NewRow—call DataTable.Rows.Add once you have set the values for the row. Changes that

you make to the data in the DataSet are not written back to the database until you call the

SqpDataAdapter.Update method.



The Code

The following example creates a DataSet and fills it with the contents of the Region table of the Northwind

sample database. The DataSet contains one DataTable, whose schema and contents are printed out. A

new record is added and an existing one modified before the changes are written back to the database.

using System;

using System.Data;

using System.Data.SqlClient;

namespace Apress.VisualCSharpRecipes.Chapter09

{

class Recipe09_12

{

static void Main(string[] args)

{

// Create a new SqlConnection object.

using (SqlConnection con = new SqlConnection())

{

// Configure the SqlConnection object's connection string.

con.ConnectionString = @"Data Source = .\sqlexpress;" +

"Database = Northwind; Integrated Security=SSPI";

// Open the database connection.

con.Open();

// Create the query string.

string query = "SELECT * from Region";

// Create the data set.

DataSet dataset = new DataSet();

// Create the SQL data adapter.

SqlDataAdapter adapter = new SqlDataAdapter(query, con);

// Create the command builder so we can do modifications.

SqlCommandBuilder commbuilder = new SqlCommandBuilder(adapter);

// Populate the data set from the database.

adapter.Fill(dataset);



463



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



// Print details of the schema.

Console.WriteLine("\nSchema for table");

DataTable table = dataset.Tables[0];

foreach (DataColumn col in table.Columns)

{

Console.WriteLine("Column: {0} Type: {1}",

col.ColumnName, col.DataType);

}

// Enumerate the data we have received.

Console.WriteLine("\nData in table");

foreach (DataRow row in table.Rows)

{

Console.WriteLine("Data {0} {1}", row[0], row[1]);

}

// Create a new row.

DataRow newrow = table.NewRow();

newrow["RegionID"] = 5;

newrow["RegionDescription"] = "Central";

table.Rows.Add(newrow);

// Modify an existing row.

table.Rows[0]["RegionDescription"] = "North Eastern";

// Enumerate the cached data again.

// Enumerate the data we have received.

Console.WriteLine("\nData in (modified) table");

foreach (DataRow row in table.Rows)

{

Console.WriteLine("Data {0} {1}", row[0], row[1]);

}

// Write the data back to the database.

adapter.Update(dataset);

}

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

}

}



464



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



Running the example produces the following results:

Schema for table

Column: RegionID Type: System.Int32

Column: RegionDescription Type: System.String



Data in table

Data 1 Eastern

Data 2 Western

Data 3 Northern

Data 4 Southern



Data in (modified) table

Data 1 North Eastern

Data 2 Western

Data 3 Northern

Data 4 Southern

Data 5 Central



Main method complete. Press Enter.



465



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



9-13. Create a DataSet Programmatically

Problem

You need to work with in-memory data without a database.



Solution

Create an instance of System.Sql.DataSet and manually populate it with instances of

System.Data.Datatable. Create a schema for each table and create rows to represent data elements.



How It Works

In the previous recipe, we demonstrated how to use the DataSet and DataTable classes as part of a

memory cache, in order to achieve disconnected data manipulation. However, you can create instances

of these classes to represent data programmatically by calling constructors for the classes directly. The

example code for this recipe illustrates how to do this in order to create the same kind of DataSet and

DataTable that we used previously.



The Code

The following code creates a DataSet that contains a single DataTable and populates it with instances of

DataRow. Once populated, the same queries, modifications, and additions are performed upon it as in the

previous recipe.

using System;

sing System.Data;

namespace Apress.VisualCSharpRecipes.Chapter09

{

class Recipe09_13

{

static void Main(string[] args)

{

// Create the data set.

DataSet dataset = new DataSet();

// Create the table and add it to the data set.

DataTable table = new DataTable("Regions");

dataset.Tables.Add(table);

// Create the colums for the table.

table.Columns.Add("RegionID", typeof(int));

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



466



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



// Populate the table.

string[] regions = { "Eastern", "Western", "Northern", "Southern" };

for (int i = 0; i < regions.Length; i++)

{

DataRow row = table.NewRow();

row["RegionID"] = i + 1;

row["RegionDescription"] = regions[i];

table.Rows.Add(row);

}

// Print details of the schema.

Console.WriteLine("\nSchema for table");

foreach (DataColumn col in table.Columns)

{

Console.WriteLine("Column: {0} Type: {1}",

col.ColumnName, col.DataType);

}

// Enumerate the data we have received.

Console.WriteLine("\nData in table");

foreach (DataRow row in table.Rows)

{

Console.WriteLine("Data {0} {1}", row[0], row[1]);

}

// Create a new row.

DataRow newrow = table.NewRow();

newrow["RegionID"] = 5;

newrow["RegionDescription"] = "Central";

table.Rows.Add(newrow);

// Modify an existing row.

table.Rows[0]["RegionDescription"] = "North Eastern";

// Enumerate the cached data again.

// Enumerate the data we have received.

Console.WriteLine("\nData in (modified) table");

foreach (DataRow row in table.Rows)

{

Console.WriteLine("Data {0} {1}", row[0], row[1]);

}

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

}

}

The program produces the following output:



467



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

9-12. Create an In-Memory Cache

Tải bản đầy đủ ngay(0 tr)

×