如何抓取第一筆資料的第一個欄位或scalar值?

来源:互联网 发布:网络平台主要做什么 编辑:程序博客网 时间:2024/05/17 22:25

<%@ Import Namespace="System.Data.SqlClient"%>
<%@ Import Namespace="System.Data"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<script language="C#" runat="server">
override protected void OnInit(EventArgs e)
{
    this.Button1.Click += new System.EventHandler(this.Button1_Click);
}

private void Button1_Click(object sender, System.EventArgs e)
{
    string strSQL = "SELECT count(*) " +
                         "FROM customers " +
                         "WHERE customerid = @customerid";

    SqlConnection con = new SqlConnection("server=(local);database=northwind;integrated security=sspi");
    SqlCommand cmd = new SqlCommand(strSQL,con);
    cmd.Parameters.Add("@customerid","ALFKI");

    try
    {
        con.Open();
        this.Label1.Text = cmd.ExecuteScalar().ToString();
    }
    catch(Exception err)
    {
        this.lbl_msg.Text = err.ToString();
        return;
    }
    finally
    {
        con.Close();
    }
}
</script>
</head>
<body>
<form id="Form1" method="post" runat="server">
<h4 style="FONT-FAMILY: Verdana">Demo : 如何抓取第一筆資料的第一個欄位或scalar值?</h4>
<h5 style="FONT-FAMILY: Arial">By Clare Hsiao 2004.09.10
</h5>
<hr size="2">
<p></p>
<asp:button id="Button1" text="Button" runat="server"></asp:button>&nbsp;<asp:label id="Label1" runat="server"></asp:label>
<p></p>
<asp:label id="lbl_msg" runat="server"></asp:label>
<p></p>
<h5>Note:</h5>
<ol>
<li>
這種寫法執行執行速度較快,尤其在使用count(*),或從Stored Procedure抓回傳值時特別好用,不需大費周章還去建立DataReader.
</li>
<li>若該SQL沒有傳回任何值,則產生Exception,所以若沒有把握一定能傳回值時,還是建議用SqlDataReader.</li>
</ol>
</form>
</body>
</html>

原创粉丝点击