블로그 이미지
Magic_kit
study 관련자료를 한곳으로 자기 개발 목적으로 재태크 재무 관리 목적으로 일상생활의 팁을 공유 하기 위하여 블로그를 개설 하였습니다.

calendar

1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28

Category

Recent Post

Recent Comment

Archive

2009. 9. 28. 12:17 .Net Project/ADO.NET 3.5
반응형
 

Category Modify, Delete .Cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Configuration;

public partial class Category_FrmCategoryModify : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    //수정
    protected void btnModify_Click(object sender, EventArgs e)
    {
        string deleteQuery = @"Update Categories Set CategoryName = 
              @CategoryName Where CategoryID = @CategoryID";
                 SqlConnection con = new SqlConnection
                 (ConfigurationManager.ConnectionStrings
                 ["ConnectionString"].ConnectionString);
        con.Open();

        SqlCommand cmd = new SqlCommand(deleteQuery, con);
                   cmd.CommandType = CommandType.Text;
      
        //파라미터 추가
        cmd.Parameters.AddWithValue
                                      ("@CategoryID", txtCategoryID.Text);
        cmd.Parameters.AddWithValue
                                      ("@CategoryName", txtCategoryName.Text);

        int recordAffected = cmd.ExecuteNonQuery();

        lblDisplay.Text = recordAffected.ToString() + "개가 변경됨";
        con.Close();


    }


    //삭제
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        //[1]변수선언부, 커넥션
        string deleteQuery =
                   "Delete Categories Where CategoryID = @CategoryID";

        SqlConnection con = new SqlConnection
                        (ConfigurationManager.ConnectionStrings
                        ["ConnectionString"].ConnectionString);
        con.Open();

        //[2]커맨드
        SqlCommand cmd = new SqlCommand(deleteQuery, con);
        cmd.CommandType = CommandType.Text;

        //[3]파라미터 추가
        cmd.Parameters.AddWithValue("@CategoryID", txtCategoryID.Text);

        //[4]실행
        int recordAffected = cmd.ExecuteNonQuery();

        //[5]마무리
        lblDisplay.Text = recordAffected.ToString() + "개가 변경됨";
        con.Close();
    }
}



반응형
posted by Magic_kit
2009. 9. 28. 10:33 .Net Project/ADO.NET 3.5
반응형
- 6가지 패던을 머리에 정리 - 
입력 : Connection -> Command -> ExecuteNonQuer()
출력 : Connection -> Command -> DataReader() -> DataBind()
상세 : Connection -> Command -> DataReader() -> Read()
수정
삭제 
검색

동기식(Synchronous) : 하나만 처리
비동기식(Asynchronous) : 다중처리, AJAX 
 

CategoryAdd 카테고리 추가.Cs



using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Category_FrmCategoryAdd : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnCategoryAdd_Click(object sender, EventArgs e)
    {
        //변수선언부
        string insertQuery =
 
        //"Insert into Categories(CategoryName) Values('컴퓨터')";

        //매개변수 처리 : 컴퓨터
        //   "Insert Into Categories(CategoryName)
                              values('" + txtCategoryName.Text + "')";

        //최적으로 사용하는 방법[추천] 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;

        //파라미터 추가
        cmd.Parameters.AddWithValue
                  ("@CategoryName", txtCategoryName.Text);

        //[3] 실행
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
        catch (SqlException se)
        {
            lblError.Text = se.Message; //에러메시지 출력
           
        }
        finally
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close(); //연결상태라면, 닫기
            }
        }
        con.Close();

    }
}


CategoryList 카테고리 리스트.Cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Category_FrmCategoryList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DisplayData();
            DisplayCount();
        }
   
    }

     //Categories 레코드 갯수 
    private void DisplayCount()
    {
        SqlConnection con = new SqlConnection
                 (ConfigurationManager.ConnectionStrings
                  ["ConnectionString"].ConnectionString);
        con.Open();

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

        cmd.CommandType = CommandType.Text;

        lblCount.Text = cmd.ExecuteScalar().ToString();
        con.Close();
    }

    //Categories 출력
    private void DisplayData()
    {
        //[1] 커넥션
        SqlConnection con = new SqlConnection
             (ConfigurationManager.ConnectionStrings
               ["ConnectionString"].ConnectionString);
        con.Open(); //열기      

        //[2] 커맨드
        SqlCommand cmd = new SqlCommand
                           ("Select *From Categories", con);
        cmd.CommandType = CommandType.Text;
       
        //[3]데이터 리더
        SqlDataReader dr = cmd.ExecuteReader();

        //[4]바인딩
        ctlCategoryList.DataSource = dr;
        ctlCategoryList.DataBind();

        //[닫기]
        dr.Close();
        con.Close();
    }
}


CategoryView 카테고리 View.Cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Category_FrmCategoryView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnCategoryID_Click(object sender, EventArgs e)
    {
        //커넥연 (데이터베이스연결)
        SqlConnection conn = new SqlConnection
                 (ConfigurationManager.ConnectionStrings
                   ["ConnectionString"].ConnectionString);
        conn.Open();

        //커맨드 : 단일 레코드
        SqlCommand cmd = new SqlCommand(
            "Select *From Categories Where
                        CategoryID = @CategoryID", conn);
        cmd.CommandType = CommandType.Text;

        //파라미터 추가
        cmd.Parameters.AddWithValue("@CategoryID", txtCategoryID.Text);

        //데이터 리더
        SqlDataReader dr = cmd.ExecuteReader();
       
        //Read() --> 문자열 정수형 인덱서 또는 GetXXX() 메서드로 읽어오기
        while (dr.Read())
        {
            //문자열 인덱서 
            this.txtCategoryID.Text = dr["CategoryID"].ToString();
           
            //정수(서수)형 처리  
            this.lblCategoryName.Text = dr[1].ToString();

            if (dr["SuperCategory"] != null) //널 값처리
            {
                this.lblSuperCategoryName.Text = dr
                                ["SuperCategory"].ToString();
            }
            this.lblCategoryAlign.Text = dr["Align"].ToString();
        }
        dr.Close();
        conn.Close();
   }
}


반응형
posted by Magic_kit
2009. 9. 25. 17:13 .Net Project/WindowServer2008
반응형
고객 상세정보 & 회원 로그인
 [17] 고객 상세정보 : 회원리스트 (회원정보, 관리자 페이지)
----------------------------------------------------------------------
Create Procedure CustomerDetail
(
     @CustomerID Int
)
As
    Select Top 1 * --모든것 출력
 From
       Customers 
       Inner Join MemberShip On Customers.CustomerID = 
       MemberShip.CustomerID
Where
     Customers.CustomerID = @CustomerID
Go
----------------------------------------------------------------------
[18] 회원 로그인
----------------------------------------------------------------------
Create Procedure CustomerLogin
(
    @UserID VarChar(50),
    @Password VarChar(50),
    @CustomerID Int Output
)
As
   Select
        @CustomerID = CustomerID
   From
        MemberShip
   Where
        UserID = @UserID
 And
        PassWord = @Password
 
 IF @@ROWCOUNT < 1
 Select 
    @CustomerID = 0
Go

주문 추가
 [19] 주문 추가 : CheckOut.aspx에서 사용
----------------------------------------------------------------------

Create Procedure OrderAdd
(
    @CustomerID Int,
    @OrderDate DateTime,
    @ShipDate DateTime,
    @TotalPrice Int,
    @OrderStatus VarChar(20),
    @Payment VarChar(20),
    @PaymentPrice Int,
    @PaymentInfo VarChar(20),
    @PaymentEndDate DateTime,
    @DeliveryInfo Int,
    @DeliveryStatus VarChar(20),
    @DeliveryEndDate DateTime,
    @OrderIP VarChar(15),
    @Password VarChar(20),
 
--위 내용은 Orders 테이블에
    @CartID  VarChar(50),
 --위 내용은 ShoppingCart와 조인걸어서 OrderDetails 테이블에
    @Message VarChar(50),
 --위 내용은 Message
    @CustomerName VarChar(50),
    @TelePhone VarChar(20),
    @MobilePhone VarChar(20),
    @ZipCode VarChar(7),
    @Address VarChar(100),
    @AddressDetail VarChar(50),
 --위 내용은 Delivery
    @OrderID Int Output
)
As
   Begin Tran AddOrder
 
 --[1] Orders 테이블에 관련 정보 기록
 Insert Into Orders
 (
    CustomerID,
    OrderDate,
    ShipDate,
    TotalPrice,
    OrderStatus,
    Payment,
    PaymentPrice,
    PaymentInfo,
    PaymentEnddate,
    DeliveryStatus,
    DeliveryEndDate,
    OrderIP,
    Password
 )
 Values
 (  
    @CustomerID,
    @OrderDate,
    @ShipDate,
    @TotalPrice,
    @OrderStatus,
    @Payment,
    @PaymentPrice,
    @PaymentInfo,
    @PaymentEnddate,
    @DeliveryStatus,
    @DeliveryEndDate,
    @OrderIP,
    @Password 
 )  
 Select
    @OrderID = @@IDENTITY --현재 바로 주문된 OrderID값 가져오기
  
 --[2] 현재 주문번호와 현재 쇼핑 카트 내용을 OrdersDetail 테이블로 저장
 Insert Into OrderDetails
 (
    OrderID,
    ProductID,
    Quantity,
    SellPrice,
    Price,
    Mileage
 )
 Select @OrderID, ShoppingCart.ProductID, Quantity, Products.SellPrice,
   (Products.SellPrice * ShoppingCart.Quantity) As Price,
   Products.Mileage
 From
  ShoppingCart Inner Join Products
  On ShoppingCart.ProductID = Products.ProductID
 Where
    CartID = @CartID 
  
--[3] 주문 실행 후 현재 카트 아이디에 해당하는 쇼핑카트 내용 지우기 
Exec ShoppingCartEmpty @CartId
   
--[4] 남기고 싶은말 저장 
Insert Into Message
 (
       OrderID, Message
 )
 Values
 (
    @OrderID, @Message
 )

 --[5]Delivery 테이블에 관련 정보 기록
 Insert Into Delivery
 (
    OrderID, CustomerName,
    TelePhone, MobilePhone,
    ZipCode, Address, AddressDetail
 )
 Values
 (
    @OrderID, @CustomerName,
    @TelePhone, @MobilePhone,
    @ZipCode, @Address, @AddressDetail
 )
    Commit Tran Addorder
Go 


 [20] 주문 리스트(회원) : OrderList.aspx
 ---------------------------------------------------------------------

Create Procedure OrderList
(
   @CustomerID Int

As
   Select
     Orders.OrderID,
     CAST(Sum(OrderDetails.Quantity * OrderDetails.SellPrice) As Int)
   As TotalPrice,
     Orders.OrderDate,
     Orders.ShipDate
 From
     Orders
 Inner Join OrderDetails On Orders.OrderID = OrderDetails.OrderID
 Group By
     CustomerID,
     Orders.OrderID,
     Orders.OrderDate,
     Orders.ShipDate
 Having
     Orders.CustomerID = @CustomerID
Go
---------------------------------------------------------------------
[21]주문 리스트(비회원)
---------------------------------------------------------------------
create Procedure OrdersListNonCustomer
(
 @OrderID Int, --주문번호
 @Password VarChar(20) --비밀번호

As
 Select
  Orders.OrderID,
  CAST(Sum(OrderDetails.Quantity * OrderDetails.SellPrice) As Int)
   As TotalPrice,
  Orders.OrderDate,
  Orders.ShipDate
 From
  Orders
 Inner Join OrderDetails On Orders.OrderID = OrderDetails.OrderID
 Group By
  Password,
  Orders.OrderID,
  Orders.OrderDate,
  Orders.ShipDate
 Having
  Orders.OrderID = @OrderID And Orders.Password = @Password
Go

 [22] 주문상세 : 특정 주문에 몇개의 제품들을 몇개씩 구매했는지 정보
----------------------------------------------------------------------

Create Procedure OrdersDetail
(
    @OrderID Int,
    @OrderDate DateTime Output,
    @ShipDate DateTime Output,
    @TotalPrice Int Output
)
As
 --[1] 현재 고객에 대한 주문일과 배송일에 대한 정보값을 반환
 Select @OrderDate = OrderDate, @ShipDate = ShipDate
 From Orders
 Where OrderID = @OrderID
 
 IF @@ROWCOUNT = 1
 Begin

 --[2] 처음으로 총 가격을 Output 매개변수 반환
 Select @TotalPrice = CAST(sum(OrderDetails.Quantity *   
              OrderDetails.SellPrice) As Int)
              From OrderDetails
              Where OrderID = @OrderID
 
 --[3] 그런다음, 주문 상세 정보값 반환
 Select
      Products.ProductID, Products.ModelName,
      Products.ModelNumber, OrderDetails.SellPrice, 
      OrderDetails.Quantity, 
    (OrderDetails.Quantity * OrderDetails.SellPrice) As ExtendedAmount
 From
    OrderDetails
    Inner Join Products On OrderDetails.ProductID = Products.ProductID
 Where
    OrderID = @OrderID
 End
Go   

고객이 이미 구입한 상품
--[23] 고객이 이미 구입한 상품 : AlsoBought.aspx
Create Procedure CustomeAlsoBought
(
    @ProductID Int
)
As
    Select Top 5
    OrderDetails.ProductID,
    Products.ModelName,
    SUM(OrderDetails.Quantity) as TotalNum
 From
    OrderDetails
    Inner Join Products On OrderDetails.ProductID = Products.ProductID
    Where OrderID IN
 (
  --ProductID에 해당하는 모든 주문에 대한 OrderID 값 반환 
    Select Distinct OrderID 
    From OrderDetails
    Where ProductID = @ProductID
 ) 
    And OrderDetails.ProductID <> @ProductID
    Group By OrderDetails.ProductID, Products.ModelName
    Order By TotalNum Desc
Go  









반응형
posted by Magic_kit
2009. 9. 25. 15:19 .Net Project/WindowServer2008
반응형
쇼핑카트 아이템 개수
 --[8] 쇼핑카트 아이템 개수 : ShoppingCart.aspx에서 사용
Create Procedure ShoppingCartItemCount
(
         @CartID VarChar(50), --현재 접속자
         @ItemCount Int Output --상품카운트
)As 
 
 Select
         @ItemCount = COUNT(ProductID)
 From
        ShoppingCart
 Where 
       CartID = @CartID
Go

쇼핑카트 리스트
 --[9] 쇼핑카트 리스트
Create Procedure ShoppingCartList
(
      @CartID VarChar(50) --현재 접속자수
)      
As
 Select
       p.ProductID, --상품고유번호
       p.ModelName, --상품명
       p.ModelNumber, --모델번호
       s.Quantity, --수량 
       p.SellPrice, --상품가격
      CAST((p.SellPrice * s.Quantity) As Int)
              As ExtendeldAmount --소계
 From
        Products p,
        ShoppingCart s
 
 Where
        p.ProductID = s.ProductID
 And 
        s.CartID = @CartID
 
Order By
         p.ModelName,
         p.ModelNumber
Go   

쇼핑카트 업데이트 & 삭제 & 쇼핑카트 총 비용  & 쇼핑카트 새로고침
 쇼핑카트 업데이트 (장바구니 재정리)
Create Procedure ShoppingCartUpdate
(
       @CartID VarChar(50), --현재접속자, 누가
       @ProductID Int,  --상품고유번호, 어떤 제품을
       @Quantity Int  --수량 몇개?
)  
As
       Update ShoppingCart
 Set
       Quantity = @Quantity
 Where
       CartID = @CartID
 And
       ProductID = @ProductID
Go     
----------------------------------------------------------------------
체크된 상품 삭제 쿼리문 
--------------------------------------------------------------------- 
Create Procedure ShoppingCartRemoveItem
(
         @CartID VarChar(50),
         @ProductID Int
 
)
As
 Delete From ShoppingCart
 Where 
       CartID = @CartID
 And
       ProductID = @ProductID
Go    
--------------------------------------------------------------------
체크된 상품 총 비용
--------------------------------------------------------------------
Create Procedure ShoppingCartTotal
(
       @CartID VarChar(50),
       @TotalCost Int Output
)    
As
    Select 
         @TotalCost = SUM(Products.SellPrice * ShoppingCart.Quantity)
 From
      ShoppingCart,
      Products
 Where
      ShoppingCart.CartID = @CartID
 And
      Products.ProductID = ShoppingCart.ProductID 
Go    
--------------------------------------------------------------------
쇼핑카트 새로고침
--------------------------------------------------------------------
--[13] 쇼핑카트 새로고침 : 비회원 - > 회원
-- 로그인 하지 않고, 장바구니 담았다가, 로그인하면,
--"고유 랜덤문자열"이 "1"과 같이 고객번호로 대체

Create Procedure ShoppingCartMigrate
(
      @OriginalCartId VarChar(50),  --세션ID
      @NewCartId VarChar(50) --고객ID
)
As
    Update
    ShoppingCart
Set
   CartId = @NewCartId
Where 
   CartId = @OriginalCartId
Go     

쇼핑카트 비우기

 --[14]쇼핑카트 비우기
Create Procedure ShoppingCartEmpty
(
    @CartID VarChar(50) --현재 접속자
)
As
   Delete From ShoppingCart
 Where
   CartID = @CartID
Go
-------------------------------------------------------------------
--[15] 퀴즈 (하루가 지난) 쇼핑 카트 ?? : 관리자 모드에서 사용
-------------------------------------------------------------------

Delete From ShoppingCart
Where
 DATEDIFF(dd,DateCreated, GetDate()) > 1 --시간차가 1일 이상인 조건
Go

Create Proc ShoppingCartRemoveAbandoned
As
 Delete From ShoppingCart
 Where
  DATEDIFF(DD, DateCreated, GETDATE()) > 1
Go


고객등록

 --[16] 고객등록 : Register.aspx에서 사용
Create Procedure CustomerAdd
(
     @CustomerName VarChar(50),
     @Phone1 VarChar(4),
     @Phone2 VarChar(4),
     @Phone3 VarChar(4),
     @Mobile1 VarChar(4),
     @Mobile2 VarChar(4),
     @Mobile3 VarChar(4),
     @Zip VarChar(7),
     @Address VarChar(100),
     @AddressDetail VarChar(100),
     @Ssn1 VarChar(6),
     @Ssn2 VarChar(7),
     @EmailAddress VarChar(50),
    @MemberDivision Int,
 --위에 매개 변수는 Customers관련, 아래 매개변수는 Membership 관련
    @UserID VarChar(25),
    @Password VarChar(100),
    @BirthYear VarChar(4),
    @BirthMonth VarChar(2),
    @BirthDay VarChar(2),
    @BirthStatus VarChar(2),
    @Gender Int,
    @Job VarChar(20),
    @Wedding Int,
    @Hobby VarChar(100),
    @Homepage VarChar(100),
    @Intro VarChar(400),
    @Mailing Int,
    @Mileage Int, 
    @CustomerID Int Output
)   
As
 Begin Tran CustomerAdd --별칭을 붙여서 트랜잭션 걸기
 --첫번째 인서트문...
 Insert Into Customers (
      CustomerName, Phone1, Phone2, Phone3, Mobile1, Mobile2,
      Mobile3, zip, Address, AddressDetail, Ssn1, Ssn2,
      EmailAddress, MemberDivision
  )
  Values (
     @CustomerName, @Phone1, @Phone2, @Phone3, @Mobile1,
     @Mobile2,@Mobile3, @zip, @Address, @AddressDetail, @Ssn1,  
     @Ssn2,@EmailAddress, @MemberDivision
  )
  --바로 위에서 실행된 쿼리문의 Identity 값 반환 
  Select @CustomerID = @@Identity 

-- 위의 내용과 같은 방식 (이와 같은 방식으로 사용 가능)
-- Select @CustomerID = MAX(CustomerID) From Customers
----------------------------------------------------------------------
 Insert Into MemberShip
 Values (
  @CustomerID, @UserID, @Password, @BirthYear, @BirthMonth, @BirthDay,
  @BirthStatus, @Gender, @Job, @Wedding,
  @Hobby, @Homepage, @Intro, @Mailing,
  0, GETDATE(), @Mileage, GETDATE()
 ) 
 Select @CustomerID
 
 If @@ERROR > 0 
--만약 에러가 발생했다면 2개 인서트 모두 리턴
         RollBack Tran CustomersAdd
    Commit Tran CustomerAdd   
Go



반응형
posted by Magic_kit