1using System;
2
3//包含了用於訪問和儲存關係型資料的基本對象和公用類,如DataSet、DataTable、DataRelation
4using System.Data;
5using System.Collections.Generic;
6using System.Linq;
7using System.Web;
8using System.Web.UI;
9using System.Web.UI.WebControls;
10using System.Data.Sql ;
11
12//包含了用於串連和操縱SQLServer資料庫的公用類,如SqlConnection、SqlCommand
13using System.Data.SqlClient;
14/// <summary>
15/// 資料提供者的兩種工作方式
16/// </summary>
17public partial class _Default : System.Web.UI.Page
18{
19 protected void Page_Load(object sender, EventArgs e)
20 {
21 /***
22 * 使用Connection對象,Command對象和DataReader對象來處理資料
23 *
24 * */
25
26 //構造用於構造建立串連的Connection對象
27 SqlConnection conn1 = new SqlConnection();
28
29 //設定連線物件的連接字串屬性ConnectionString
30 conn1.ConnectionString = "Data Source=SHERRY;Initial Catalog=test;Integrated Security=True";
31
32 //構造命令對象Command對象
33 SqlCommand cmd1 = new SqlCommand();
34
35 //設定命令對象的CommandText屬性
36 cmd1.CommandText = "select *from [user]";
37
38 //設定命令對象的Connection屬性,該屬性工作表示命令對象是向哪一個串連發送命令
39 cmd1.Connection = conn1;
40
41 //開啟資料庫連接
42 conn1.Open();
43
44 //執行命令,並且將返回結果指向DataReader對象
45 SqlDataReader reader = cmd1.ExecuteReader();
46
47 //用GridView控制項顯示資料
48 GridView1.DataSource = reader;
49 GridView1.DataBind();
50
51 //關閉串連
52 conn1.Close();
53
54 /***
55 * 使用DataAdapter對象和DataSet對象來處理資料
56 *
57 * */
58
59 //定義資料配接器對象
60 SqlDataAdapter adapter = new SqlDataAdapter();
61
62 //定義資料集對象
63 DataSet dsDataSet = new DataSet();
64
65 //定義資料連線對象,並設定連接字串屬性
66 SqlConnection conn2 = new SqlConnection();
67 conn2.ConnectionString = "Data Source=SHERRY;Initial Catalog=test;Integrated Security=True";
68
69 //定義命令對象,並設定相關屬性
70 SqlCommand cmd2 = new SqlCommand();
71 cmd2.CommandText = "select *from [user]";
72 cmd2.Connection = conn2;
73
74 //將查詢命令設定為資料配接器對象的SelectCommand屬性
75 adapter.SelectCommand = cmd2;
76
77 //定義DataTable對象
78 DataTable table = new DataTable();
79
80 //使用資料配接器對象的Fill方法填充資料集
81 adapter.Fill(dsDataSet, "table");
82
83 //放入DataTable中
84 table = dsDataSet.Tables["table"];
85
86 //輸出DataSet中DataTable的預設視圖
87 this.GridView2.DataSource = table.DefaultView;
88 this.GridView2.DataBind();
89 }
90
91}