Thứ Sáu, 21 tháng 2, 2014

4.Tạo lớp kết nối và truy vấn dữ liệu: DataLayer



4. Tạo lớp kết nối và truy vấn dữ liệu: DataLayer

- Tạo thư mục DataLayer

- Tạo lớp hỗ trợ kết nối dữ liệu DataAccessHelper

- Tên file: DataAccessHelper.cs, dạng Class Library.
- Nội dung coding:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace BookShop.DataLayer
{
    class DataAccessHelper
    {
        #region 1. Khai báo các thành viên dữ liệu
        SqlConnection conn;
        SqlCommand cmd;
        #endregion

        #region 2. Các phương thức khởi tạo
        public DataAccessHelper()
        {
            conn = new SqlConnection(@"Server=.\SQLEXPRESS; Database=BookShopDB; Integrated Security = True;");

        }
        #endregion

        #region 3. Các phương thức thao tác với CSDL

        ///


        /// Phương thức mở kết nối tới CSDL
        ///

        private void Open()
        {
            if (conn.State == System.Data.ConnectionState.Closed)
                conn.Open();
        }

        ///


        /// Phương thức ngắt kết nối với CSDL
        ///

        private void Close()
        {
            if (conn.State == System.Data.ConnectionState.Open)
                conn.Close();
        }
      
        ///


        /// Phương thức lấy về một giá trị từ mệnh đề SELECT
        ///

        /// Câu lệnh SELECT
        /// Một đối tượng

        public object GetValue(string query)
        {
            Open();
            cmd = new SqlCommand(query, conn);
            return cmd.ExecuteScalar();
        }

        public DataTable GetDateTable(string select)
        {
            SqlDataAdapter da = new SqlDataAdapter(select, conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
        }

        public int ExecuteNonQuery(string query)
        {
            Open();
            cmd = new SqlCommand(query, conn);
            return cmd.ExecuteNonQuery();
        }
        #endregion
    }
}

- Tạo lớp kết nối dữ liệu sách BookDAL

- Nội dung coding BookDAL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BookShop.Entities;
using System.Data;

namespace BookShop.DataLayer
{
    class BookDAL
    {
        DataAccessHelper db = new DataAccessHelper();

        public Book GetBookByID(int id)
        {
            Book bk = new Book();

            List<Book> list = GetList();
            foreach(Book b in list)
                if (b.BookID == id)
                {
                    bk = b;
                    break;
                }

            return bk;
        }


        public static List<Book> GetList()
        {
            DataAccessHelper db = new DataAccessHelper();
            DataTable dt = db.GetDateTable("SELECT * FROM Books");

            List<Book> list = new List<Book>();

            foreach (DataRow row in dt.Rows)
            {
                list.Add(new Book(row));
            }

            return list;
        }


        public static List<Book> GetListByName(string keyword)
        {
            DataAccessHelper db = new DataAccessHelper();
            DataTable dt = db.GetDateTable("SELECT * FROM Books WHERE BookID like '%"+keyword+"%' or BookName LIKE '%" + keyword + "%'");

            List<Book> list = new List<Book>();

            foreach (DataRow row in dt.Rows)
            {
                list.Add(new Book(row));
            }
            return list;
        }

        public bool Insert(Book bk)
        {
            int count = db.ExecuteNonQuery("INSERT INTO Books VALUES(N'" + bk.BookName + "',N'" + bk.Author + "'," + bk.Amount + "," + bk.Price + ")");
            return count > 0;
        }

        public bool Update(Book bk)
        {
            int count = db.ExecuteNonQuery("UPDATE Books SET BookName = N'" + bk.BookName + "',Author = N'" + bk.Author + "',Amount=" + bk.Amount + ",Price=" + bk.Price + " WHERE BookID = "+bk.BookID);
            return count > 0;
        }

        public bool Delete(Book bk)
        {
            int count = db.ExecuteNonQuery("DELETE Books WHERE BookID=" + bk.BookID);
            return count > 0;
        }

    }
}

- Tạo lớp kết nối OrderDAL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BookShop.Entities;
using System.Data;

namespace BookShop.DataLayer
{
    class OrderDAL
    {
        DataAccessHelper db = new DataAccessHelper();

        public List<Order> GetListOrders()
        {
                   
            DataTable dt = db.GetDateTable("SELECT * FROM Orders ORDER BY OrderID DESC");

            List<Order> list = new List<Order>();

            foreach (DataRow row in dt.Rows)
            {
                list.Add(new Order(row));
            }

            return list;
      
        }


        public List<Order> GetListOrderByDate(DateTime orderDate)
        {

            DataTable dt = db.GetDateTable("SELECT * FROM Orders WHERE CONVERT(date, OrderDate) ='" + orderDate.ToString("yyyy-MM-dd") + "' ORDER BY OrderID DESC");

            List<Order> list = new List<Order>();

            foreach (DataRow row in dt.Rows)
            {
                list.Add(new Order(row));
            }

            return list;

        }

        public bool Insert(Order od)
        {
            try
            {
                db.ExecuteNonQuery("INSERT INTO Orders VALUES(N'" + od.CustomerName + "','" + od.OrderDate.ToString("yyyy-MM-dd hh:mm:ss tt") + "'," + od.Total + ")");

                int id = (int)db.GetValue("SELECT MAX(OrderID) FROM Orders");

                foreach (OrderDetail d in od.ListOrderDetail)
                {
                    db.ExecuteNonQuery("INSERT INTO OrderDetails VALUES(" + id + "," + d.BookID + "," + d.Quantity + "," + d.Price + "," + d.TotalPrice + ")");
                }

                return true;
            }
            catch
            {
                return false;
            }

        }
    }

}

3.Quản lý hóa đơn bán sách (4)



3. Tạo lớp khai báo dữ liệu

- Tạo thư mục Entities (Bấm phải chuột vào dự án và chọn lệnh Add Folder)

- Khai báo lớp Book

Dạng Class Library, trong thư mục Entities (file book.cs), nội dung coding:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Data;

namespace BookShop.Entities
{
    class Book
    {
        private int _bookID;

        public int BookID
        {
            get { return _bookID; }
            set { _bookID = value; }
        }

        private string _bookName;

        public string BookName
        {
            get { return _bookName; }
            set { _bookName = value; }
        }

        private string _author;

        public string Author
        {
            get { return _author; }
            set { _author = value; }
        }

        private int _amount;

        public int Amount
        {
            get { return _amount; }
            set { _amount = value; }
        }

        private int _price;

        public int Price
        {
            get { return _price; }
            set { _price = value; }
        }

        public Book()
        {
        }

        public Book(string bookName, string author, int amount, int price)
        {
            this._bookName = bookName;
            this._author = author;
            this._amount = amount;
            this._price = price;
        }

        public Book(int bookID, string bookName, string author, int amount, int price)
        {
            this._bookID = bookID;
            this._bookName = bookName;
            this._author = author;
            this._amount = amount;
            this._price = price;
        }


        public Book(DataRow row)
        {
            this._bookID = (int)row["BookID"];
            this._bookName = row["BookName"].ToString();
            this._author = row["Author"].ToString();
            this._amount = (int)row["Amount"];
            this._price = (int)row["Price"];
        }
    }
}


- Khai báo lớp Order, dạng Class Library, trong thư mục Entities (file order.cs), nội dung coding:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace BookShop.Entities
{
    class Order
    {
        private int _orderID;

        public int OrderID
        {
            get { return _orderID; }
            set { _orderID = value; }
        }

        private string _customerName;

        public string CustomerName
        {
            get { return _customerName; }
            set { _customerName = value; }
        }

        private DateTime _orderDate;

        public DateTime OrderDate
        {
            get { return _orderDate; }
            set { _orderDate = value; }
        }

        private int _total;

        public int Total
        {
            get { return _total; }
            set { _total = value; }
        }

        private List<OrderDetail> _listOrderDetail;

        internal List<OrderDetail> ListOrderDetail
        {
            get { return _listOrderDetail; }
            set { _listOrderDetail = value; }
        }

        public Order()
        {

        }

        public Order(string customerName, DateTime orderDate, int total)
        {
            this._customerName = customerName;
            this._orderDate = orderDate;
            this._total = total;
        }

        public Order(DataRow row)
        {
            this._orderID = (int)row["OrderID"];
            this._customerName = row["CustomerName"].ToString();
            this._orderDate = DateTime.Parse(row["OrderDate"].ToString());
            this._total = (int)row["Total"];
        }

    }
}

- Khai báo lớp OrderDetail, dạng Class Library, trong thư mục Entities (file orderdetail.cs), nội dung coding:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace BookShop.Entities
{
    class OrderDetail
    {
        private int _recordID;

        public int RecordID
        {
            get { return _recordID; }
            set { _recordID = value; }
        }

        private int _orderID;

        public int OrderID
        {
            get { return _orderID; }
            set { _orderID = value; }
        }

        private int _bookID;

        public int BookID
        {
            get { return _bookID; }
            set { _bookID = value; }
        }

        private int _quantity;

        public int Quantity
        {
            get { return _quantity; }
            set { _quantity = value; }
        }

        private int _price;

        public int Price
        {
            get { return _price; }
            set { _price = value; }
        }

        private int _totalPrice;

        public int TotalPrice
        {
            get { return _totalPrice; }
            set { _totalPrice = value; }
        }

        public OrderDetail()
        {
        }


        public OrderDetail(DataRow row)
        {
            this._recordID = (int)row["RecordID"];
            this._orderID = (int)row["OrderID"];
            this._bookID = (int)row["BookID"];
            this._quantity = (int)row["Quantity"];
            this._price = (int)row["Price"];
            this._totalPrice = (int)row["TotalPrice"];
        }

    }

}

2. Tạo Solution mới (3)



2. Tạo Solution BOOKSHOP

Tạo các thư mục trong Solution BOOKSHOP như sau:


Trong đó:
- Utilities: chứa lớp tiện ích định dạng dữ liệu
- Entities: chứa lớp định nghĩa dữ liệu
- DataLayer: chứa lớp định nghĩa các hàm thao tác dữ liệu
- BusinessLayer: chứa lớp thao tác dữ liệu

- PressentationLayer: lớp chứa các form thao tác trực tiếp giữa người dùng và CSDL

1. Cơ sở dữ liệu sử dụng trong dự án phần mềm bán sách





1. Tạo CSDL BookShop


Cấu trúc định nghĩa các bảng bằng SQL

TABLE [Books]
            [BookID] [int] IDENTITY(1,1) NOT NULL,
            [BookName] [nvarchar](250) NOT NULL,
            [Author] [nvarchar](500) NOT NULL,
            [Amount] [int] NOT NULL,
            [Price] [int] NOT NULL,

TABLE [dbo].[Orders]
            [OrderID] [int] IDENTITY(1,1) NOT NULL,
            [CustomerName] [nvarchar](100) NULL,
            [OrderDate] [datetime] NULL,
            [Total] [int] NULL,

TABLE [OrderDetails]
            [RecordID] [int] IDENTITY(1,1) NOT NULL,
            [OrderID] [int] NOT NULL,
            [BookID] [int] NOT NULL,
            [Quantity] [int] NOT NULL,
            [Price] [int] NOT NULL,

            [TotalPrice] [int] NOT NULL,