1
using
System;
2
3
//
包含了用于访问和存储关系型数据的基本对象和公共类,如DataSet、DataTable、DataRelation
4
using
System.Data;
5
using
System.Collections.Generic;
6
using
System.Linq;
7
using
System.Web;
8
using
System.Web.UI;
9
using
System.Web.UI.WebControls;
10
using
System.Data.Sql ;
11
12
//
包含了用于连接和操纵SQLServer数据库的公共类,如SqlConnection、SqlCommand
13
using
System.Data.SqlClient;
14
/// <summary>
15
/// 数据提供程序的两种工作方式
16
/// </summary>
17
public
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
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91
