Blog Content

    티스토리 뷰

    20.ADO.NET - SqlParamter

    반응형
    FrmSqlParamter.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="txtCategoryName" runat="server"></asp:TextBox>

            <asp:Button ID="btnAdd" runat="server" Text="추가" onclick="btnAdd_Click" />

            <br />

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

            </asp:GridView>

       

        </div>

        </form>

    </body>

    </html>


    FrmSqlParamter.aspx.cs

    protected void Page_Load(object sender, EventArgs e)

    {

       if (!Page.IsPostBack)

       {

           DisplayData();

       }

    }

     

    private void DisplayData() {

       SqlConnection con = new SqlConnection(

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

       con.Open();

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

       SqlDataAdapter da = new SqlDataAdapter(cmd);

       DataSet ds = new DataSet();

       da.Fill(ds, "Categories");

       this.ctlCategoryList.DataSource = ds.Tables[0];

       this.ctlCategoryList.DataBind();

       con.Close();

    }

     

    protected void btnAdd_Click(object sender, EventArgs e) {

       SqlConnection con = new SqlConnection();

       con.ConnectionString =

           ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

       con.Open();

       SqlCommand cmd = new SqlCommand();

       cmd.Connection = con;

       cmd.CommandText = "Insert Into Categories(CategoryName) Values(@CategoryName)";

       cmd.CommandType = CommandType.Text;

     

       // 파라미터 추가하는 첫번째 방법

       //cmd.Parameters.AddWithValue("@CategoryName", txtCategoryName.Text);

      

       // 파라미터 추가하는 두번째 방법

       //cmd.Parameters.Add("@CategoryName", SqlDbType.VarChar, 50);

       //cmd.Parameters["@Categoryname"].Value = txtCategoryName.Text;

      

       // SqlParameter 클래스 사용 : SP OUTPUT매개변수 처리시 주로 사용

     

       SqlParameter paramterCategoryName =

           new SqlParameter("@CategoryName", SqlDbType.VarChar, 50);

       paramterCategoryName.Direction = ParameterDirection.Input; // 입력용

       paramterCategoryName.Value = txtCategoryName.Text;

       cmd.Parameters.Add(paramterCategoryName);

     

       cmd.ExecuteNonQuery();

       con.Close();

       DisplayData(); // 새로 출력

    }


    결과화면

    [그림20-1]



    반응형

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

    22.ADO.NET - MakeDataSet  (0) 2009.09.29
    21.ADO.NET - DataTableSelect  (0) 2009.09.29
    -- 주소록 DB사용  (0) 2009.09.29
    19.ADO.NET - RowFilter  (0) 2009.09.28
    18.ADO.NET - DataRow  (0) 2009.09.28

    Comments