1
<%@ Import Namespace="System.Data.SqlClient"%>
2
<%@ Import Namespace="System.Data"%>
3
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
4
<html>
5
<head>
6
<meta http-equiv="Content-Type" content="text/html; charset=big5">
7
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
8
<script language="C#" runat="server">
9
override protected void OnInit(EventArgs e) {
10
this.Button1.Click += new System.EventHandler(this.Button1_Click);
11
}
12
13
private void Button1_Click(object sender, System.EventArgs e) {
14
string strSQL = "SELECT count(*) " +
15
"FROM customers " +
16
"WHERE customerid = @customerid";
17
18
SqlConnection con = new SqlConnection("server=(local);database=northwind;integrated security=sspi");
19
SqlCommand cmd = new SqlCommand(strSQL,con);
20
cmd.Parameters.Add("@customerid","ALFKI");
21
22
try {
23
con.Open();
24
this.Label1.Text = cmd.ExecuteScalar().ToString();
25
}
26
catch(Exception err) {
27
if (Trace.IsEnabled)
28
Trace.Warn(err.ToString());
29
30
return;
31
}
32
finally {
33
con.Close();
34
}
35
}
36
</script>
37
</head>
38
<body>
39
<form id="Form1" method="post" runat="server">
40
<h4 style="FONT-FAMILY: Verdana">Demo : 如何抓取第一筆資料的第一個欄位或scalar值?</h4>
41
<h5 style="FONT-FAMILY: Arial">By Clare Hsiao 2004.09.10</h5>
42
<hr size="2">
43
<p></p>
44
<asp:button id="Button1" text="Button" runat="server"></asp:button>
45
<asp:label id="Label1" runat="server"></asp:label>
46
<p></p>
47
<h5>Note:</h5>
48
<ol>
49
<li>
50
這種寫法執行執行速度較快,尤其在使用count(*),或從Stored Procedure抓回傳值時特別好用,不需大費周章還去建立DataReader.
51
</li>
52
<li>
53
若該SQL沒有傳回任何值,則產生Exception,所以若沒有把握一定能傳回值時,還是建議用SqlDataReader.</li>
54
</ol>
55
</form>
56
</body>
57
</html>
58

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
