ASP.NET

11.ADO.NET - ExecuteScalar

Godffs 2009. 9. 25. 10:40
반응형
예제를 위해서 Web.config에 데이터베이스 연결문자열을 입력합니다. [ Web.config ]
FrmExecuteScalar.aspx

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

   

        현재 카테고리 개수 :

        <asp:Label ID="lblCategoryCount" runat="server" Text=""></asp:Label>

        <br />

        <br />

        등록된 상품 개수 :

        <asp:Label ID="lblProductCount" runat="server" Text=""></asp:Label>

   

    </div>

    </form>

</body>

</html>


FrmExecuteScalar.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{

   DisplayCategoryCount();

   DisplayProductCount();

}


private void DisplayProductCount() {

   SqlConnection con = new SqlConnection(

       ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);


   con.Open();

 

   SqlCommand cmd = new SqlCommand("Select Count(*) From Categories", con);

 

   //[!] 스칼라값 실행

   this.lblProductCount.Text = cmd.ExecuteScalar().ToString(); // 실행결과를문자열로

 

   con.Close();

}


private void DisplayCategoryCount()

{

   using (SqlConnection con = new SqlConnection(

       ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))

   {

       con.Open();

       SqlCommand cmd = new SqlCommand(

           "Select Count(*) As Cnt From Categories", con);

 

       SqlDataReader dr = cmd.ExecuteReader();

       while (dr.Read()) {

           lblCategoryCount.Text = dr["Cnt"].ToString(); // 카운트 출력

       }

   } // con.Close();   

}


결과확인

[그림11-1]



반응형