2012年12月19日 星期三 天气小雨
前面学习了数据的选择和查询,并初步了解了DataSet。现在将要更深入的学习DataSet,通过DataSet来构建应用程序并将数据读入DataSet方法。
今天,学习DataSet类的层次结构。
DataSet是将数据驻存在内存中,可以完整的、一致的提供数据的关系模型。也就是说将数据库中的表读取到DataSet中后,在DataSet中的数据与数据库表中的数据是一致的。
DataSet类中,.NET类库提供了许多有用的属性和方法。
下面是一个运用DataSet的实例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace 构造DataSet
{
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Product");
DataColumn dcProductID = new DataColumn("ProductID", typeof(int));
DataColumn dcProductName = new DataColumn("ProductName", typeof(string));
dcProductName.MaxLength = 100;
DataColumn dcReleaseDate = new DataColumn("ReleaseDate", typeof(DateTime));
dt.Columns.Add(dcProductID);
dt.Columns.Add(dcProductName);
dt.Columns.Add(dcReleaseDate);
dt.PrimaryKey = new DataColumn[] { dcProductID };
dt.Constraints.Add(new UniqueConstraint(dcProductName));
dt.Rows.Add(new object[] { 1, "4×4 EVO 2", DateTime.Now });
dt.Rows.Add(new object[] { 2, "Halo 3", DateTime.Now });
dt.Rows.Add(new object[] { 3, "Paperboy", DateTime.Now });
ds.Tables.Add(dt);
PrintToConsole(ds);
PrintToConsole(dt);
}
public static void PrintToConsole(DataSet ds)
{
ConsoleColor old = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("DataSetName:{0}", ds.DataSetName);
Console.WriteLine("Has Changes:{0}", ds.HasChanges());
Console.ForegroundColor = old;
Console.WriteLine("-".PadRight(79, '-'));
}
public static void PrintToConsole(DataTable dt)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("DataTable:{0}", dt.TableName);
Console.WriteLine("Has Changes:{0}", (dt.GetChanges().Rows.Count > 0));
Console.WriteLine("-".PadRight(79, '-'));
Console.ForegroundColor = ConsoleColor.Cyan;
string colHeader = string.Empty;
foreach (DataColumn dc in dt.Columns)
{
colHeader = colHeader + dc.ColumnName.PadRight(FiveOrLength(dc));
}
colHeader = colHeader + "\tRowState";
Console.WriteLine(colHeader);
Console.WriteLine("-".PadRight(79, '-'));
foreach (DataRow dr in dt.Rows)
{
PrintToConsole(dr);
}
Console.WriteLine();
}
public static void PrintToConsole(DataRow dr)
{
Console.ForegroundColor = ConsoleColor.White;
string row = string.Empty;
foreach (DataColumn dc in dr.Table.Columns)
{
row = row + dr[dc].ToString().PadRight(FiveOrLength(dc));
}
row = row + "\t\t" + dr.RowState.ToString();
Console.WriteLine(row);
}
public static int FiveOrLength(DataColumn dc)
{
if (dc.DataType == typeof(DateTime))
{
return 20;
}
else if (dc.MaxLength < 5)
{
return 5;
}
else
{
return 20;
}
}
}
}
运行结果: