zoukankan      html  css  js  c++  java
  • [ADO.NET][Command]如何抓取第一筆資料的第一個欄位或scalar值?

     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>&nbsp;
    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
  • 相关阅读:
    URAL 2067 Friends and Berries (推理,数学)
    URAL 2070 Interesting Numbers (找规律)
    URAL 2073 Log Files (模拟)
    URAL 2069 Hard Rock (最短路)
    URAL 2068 Game of Nuts (博弈)
    URAL 2066 Simple Expression (水题,暴力)
    URAL 2065 Different Sums (找规律)
    UVa 1640 The Counting Problem (数学,区间计数)
    UVa 1630 Folding (区间DP)
    UVa 1629 Cake slicing (记忆化搜索)
  • 原文地址:https://www.cnblogs.com/clare/p/207660.html
Copyright © 2011-2022 走看看