Blog Content

    티스토리 뷰

    12.ADO.NET - Parameters

    반응형
    입력한 범위에 대해서 값을 가져오는 예제입니다.
    Web.config에 [ 데이터베이스 연결문자열 지정 ]

    FrmParameters.aspx

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

    <head runat="server">

        <title></title>

    </head>

    <body>

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

        <div>

       

            <asp:TextBox ID="txtFirst" runat="server"></asp:TextBox>

            ~<asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>

            사이의&nbsp; 카테고리 출력

            <asp:Button ID="btnSelect" runat="server" Text="가져오기"

                Font-Bold="true" ForeColor="Red" Font-Underline="true"

                BackColor="Yellow" BorderColor="Blue" onclick="btnSelect_Click" />

            <br />

            <asp:GridView ID="ctlCategoryList" runat="server">

            </asp:GridView>

       

        </div>

        </form>

    </body>

    </html>


    FrmParameters.aspx.cs

    protected void btnSelect_Click(object sender, EventArgs e)

    {

       //[1] 변수 선언부

       string first = txtFirst.Text;

       string second = txtSecond.Text;

       //[2] 커넥션

       using (SqlConnection con = new SqlConnection(

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

       {

           con.Open();

           //[3] 커멘드

           SqlCommand cmd = new SqlCommand();

           cmd.Connection = con;

           cmd.CommandText =

               //"Select * From Categories Where CategoryID Between 1 And 20"; //[1]

               //"Select * From Categories Where CategoryID Between " + first //[2]

               //    + " And " + second + "";

               //String.Format(@"

               //    Select * From Categories

               //    Where CategoryID Between {0} And {1}", first, second); //[3]

               "Select * From Categories Where Num Between @First And @Second";//[4]

     

           //[!] 파라미터 추가

           cmd.Parameters.AddWithValue("@First", first); // .NET2.0

           //cmd.Parameters.AddWithValue("@Second", second);   

           cmd.Parameters.Add("@Second", System.Data.SqlDbType.Int); // .NET1.X ->

           cmd.Parameters["@Second"].Value = second;

     

           //[4] 데이터리더

           SqlDataReader dr = cmd.ExecuteReader();

           //[5] 바인딩

           ctlCategoryList.DataSource = dr;

           ctlCategoryList.DataBind();

           //[6] 마무리

           dr.Close();

       }

    }


    결과확인

    [그림12-1]



    반응형

    'ASP.NET' 카테고리의 다른 글

    14.ADO.NET - Transaction  (0) 2009.09.28
    13.ADO.NET - DbProviderFactory  (0) 2009.09.25
    11.ADO.NET - ExecuteScalar  (0) 2009.09.25
    10.ADO.NET - ConfigurationManager  (0) 2009.09.25
    09.ADO.NET - ADO.NET ( 입력값 저장 )  (0) 2009.09.25

    Comments