13. 입력(Insert문을 넣어서 카테고리 추가하기)
.NET프로그래밍/ADO.NET 2009. 9. 28. 09:45 |==>[FrmCategoryAdd.aspx] 소스 및 디자인
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmCategoryAdd.aspx.cs" Inherits="FrmCategoryAdd" %>
<!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:TextBox ID="txtCategoryName" runat="server"></asp:TextBox>
<asp:Button ID="btnAdd" runat="server" Text="입력" onclick="btnAdd_Click" />
<asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label>
</div>
</form>
</body>
</html>
-------------------------------------------------------------------------------------
==>[FrmCategoryAdd.aspx.cs]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data; //
using System.Data.SqlClient; //
using System.Configuration; //
public partial class FrmCategoryAdd : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
//[0] 변수 선언부
string insertQuery =
//[1] "Insert Into Categories(CategoryName) Values('컴퓨터')";
//[2] 매개변수 처리 : 컴퓨터 -> " + 변수 + "로 대체 ==> 이런방법은 쓰지 말 것!(SQL인젝션공격에 매우 취약함!)
//"Insert Into Categories(CategoryName) Values('" + txtCategoryName.Text + "')";
//[3] Named 매개변수 처리 : @변수
"Insert Into Categories(CategoryName) Values(@CategoryName)";
//[1] 커넥션
SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
//[2] 커멘드
SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.CommandType = CommandType.Text;
//[3] 파라미터 추가
cmd.Parameters.AddWithValue("@CategoryName", txtCategoryName.Text);
//[4] 실행
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException se)
{
lblError.Text = se.Message; // 에러메시지 출력
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close(); // 연결상태라면, 닫기
}
}
}
}
-------------------------------------------------------------------------------------
[실행결과]
--> 웹페이지에서 '텍스트박스'에 "컴퓨터"를 입력하고 "입력"버튼 클릭.
--> [SQL Server] - [Market] - [dbo.Categories]테이블을 실행해보면 테이블 맨아래 "CategoryID"가 26인 값에 "컴퓨터"가 입력(추가)된 것을 볼 수 있다.
'.NET프로그래밍 > ADO.NET' 카테고리의 다른 글
15. 상세보기 (0) | 2009.09.28 |
---|---|
14. 출력(CategoryList) (0) | 2009.09.28 |
12. DbProviderFactory 클래스 (0) | 2009.09.25 |
11. 파라미터(Parameters) 사용 (0) | 2009.09.25 |
10. SqlCommand..::.ExecuteScalar 메서드 (0) | 2009.09.25 |