您的位置:首页 > 其它

ADO.NET笔记——使用DataSet返回数据

2015-03-20 20:23 405 查看
相关知识:

DataSet和DataAdapter的内部结构:

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
string strConn = @"server=Joe-PC;database=AdventureWorks_WroxSSRS2012;uid=sa;pwd=root";
SqlConnection conn = new SqlConnection(strConn);

DataSet ds = new DataSet();

string strCmd1 = "SELECT ProductCategoryID,Name FROM Production.ProductCategory";
SqlDataAdapter da1 = new SqlDataAdapter(strCmd1, conn);
// 将第一个查询结果集合填入DataSet中,并且将DataTable命名为"Category"
da1.Fill(ds, "Category");

string strCmd2 = "SELECT ProductSubcategoryID,ProductCategoryID,Name From Production.ProductSubcategory";
SqlDataAdapter da2 = new SqlDataAdapter(strCmd2, conn);
// 将第二个查询结果集合填入DataSet中,并且将DataTable命名为"Subategory"
da2.Fill(ds, "Subcategory");

// 使用视图
// 打印表中的数据
Console.WriteLine("主类别表:");
DataTable dt1 = ds.Tables["Category"];//获得Category表
DataView dv1 = new DataView(dt1); //创建视图
dv1.Sort = "ProductCategoryID ASC"; //设置排序规则
foreach (DataRowView drv in dv1)
{
Console.WriteLine("{0}:{1}", drv[0], drv["Name"]);
}

Console.WriteLine("");

Console.WriteLine("过滤后的子类别表:");
DataTable dt2 = ds.Tables["Subcategory"];
DataView dv2 = new DataView(dt2);
dv2.RowFilter = "ProductSubcategoryID>10";//设置过滤条件
dv2.Sort = "ProductSubcategoryID ASC";
foreach (DataRowView drv in dv2)
{
Console.WriteLine("{0}:{1}", drv[0], drv["Name"]);
}

Console.WriteLine("");

// 在两个表之间建立关联
DataRelation relation = new DataRelation("ProductCategory_ProductSubcategory",
dt1.Columns["ProductCategoryID"], dt2.Columns["ProductCategoryID"]);
ds.Relations.Add(relation);//将关联添加到DataSet的集合中
try
{
for (int i = 0; i < dt1.Rows.Count; i++)
{
DataRow dri = dt1.Rows[i];
//根据关联找到数据相关的子类别数据
DataRow[] subRows = dri.GetChildRows(relation);
Console.WriteLine("{0}的子类别信息:", dri["Name"]);
foreach (DataRow dr in subRows)
{
Console.WriteLine("{0}:{1}", dr[0], dr["Name"]);
}
Console.WriteLine("");
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: