==> [FrmExecuteScalar.aspx]  소스 및 디자인

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmExecuteScalar.aspx.cs" Inherits="FrmExecuteScalar" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<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]




using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

public partial class FrmExecuteScalar : System.Web.UI.Page

{

    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 Products", 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();

    }

}

 

 

 

// 단일값 반환(처리) 할 때는 ExecuteScalar()로 처리하면된다.

 

// SqlCommand..::.ExecuteScalar 메서드- 쿼리를 실행하고 쿼리에서 반환된 결과 집합의 첫 번째 행의 첫 번째 열을 반환합니다. 추가 열이나 행은 무시됩니다.

 

 


=====================================================================================




[실행결과]

--> 아래그림은 [FrmExecuteScalar.aspx.cs]에서 "cmd.ExecuteScalar()"메서드를 사용하여 "등록된 상품 개수"라고 쓰여있는 레이블인 "lblProductCount"에 등록된 상품 개수의 "단일값"(=스칼라값 / 집계함수인 "Count()"는 단일값을 반환한다.)을 반환하여 출력하도록 하였으며("결과값:31"), "현재 카테고리 개수"라고 쓰여있는 레이블인 "lblCategoryCount"에는 "cmd.ExecuteReader()"메서드를 사용하여 현재 카테고리 개수의 "단일값"(카운트, 집계함수Count())을 출력해보았다.("결과값:20")










Posted by holland14
: