三層架構


       ...O(∩_∩)O...Happy New Year!!...O(∩_∩)O ...好久沒寫博客了,因為漏掉了很多的知識沒有總結,所以不知道該從哪寫起了,剛好今天是元旦假期后的第一天,所以還是把之前學的一個重點寫一下吧。

三層架構理論:

三層架構就是將整個業務應用划分為:表現層(UI層)、業務邏輯層(BLL層)、數據訪問層(DAL層),微軟推薦的分層式結構一般分為三層,從下至上分別為:數據訪問層、業務邏輯層(又或稱為領域層)、表示層。

 

各層的作用

1:數據訪問層:主要是對原始數據(數據庫或者文本文件等存放數據的形式)的操作層,而不是指原始數據,也就是說,是對數據的操作,而不是數據庫,具體為業務邏輯層或表示層提供數據服務.
 
2:業務邏輯層:主要是針對具體的問題的操作,也可以理解成對數據層的操作,對數據業務邏輯處理,如果說數據層是積木,那邏輯層就是對這些積木的搭建。主要負責對數據層的操作。也就是說把一些數據層的操作進行組合。
 
3:表示層:主要表示WEB方式,也可以表示成WINFORM方式,WEB方式也可以表現成:aspx,如果邏輯層相當強大和完善,無論表現層如何定義和更改,邏輯層都能完善地提供服務。主要對用戶的  請求接受,以及數據的返回,為客戶端提供應用程序的訪問。
 

三層架構實操(增刪改查的一個小程序)

首先搭建三層架構,在解決方案中添加UI層,BLL業務邏輯層,DAL數據訪問層,以及它們公用的MODEL層。它們之間的關系是UI層引用MODEL層,BLL層;BLL層引用MODEL層,DAL層;DAL層引用MODEL層。

* 在UI層下的App.config配置文件下添加數據庫連接

 

<connectionStrings>
    <add name="sql" connectionString="Data Source=.;Initial Catalog=UserInfo;Integrated Security=True"/>
  </connectionStrings>

 

 *Model層里放置的是屬性。

namespace Model
{
   public class Tmodel
    {
       //屬性名和數據庫中表的字段名相對
       public  Guid   Id    { set; get; }
       public  string Pname { set; get; }
       public  string Pwd    { set; get; }
       public  int    Pheight{ set; get; }
       public  bool   Pgender{ set; get; }
       public  string Padderss{ set; get; }
       public  DateTime Pbirthday{ set; get; }

    }
}

 

 *DAL層中添加兩個類,一個DBHelper,一個Tdal

DBHelper類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace DAL
{
  static public class DBHerper
    {
      public static  string connstr = ConfigurationManager.ConnectionStrings["sql"].ToString(); //添加鏈接字符串

      //除了select查詢外用於執行對數據表內容的操作
      public static int ExecuteNunQuery(string cmdtext, CommandType type,params SqlParameter[]parms)
      {
          using (SqlConnection conn=new SqlConnection (connstr))
          {
              conn.Open();
              using (SqlCommand  comm=new SqlCommand (cmdtext,conn))
              {
                  comm.CommandType = type;
                  comm.Parameters.AddRange(parms);
                  return comm.ExecuteNonQuery(); 
              }
          }
      
      
      }
     //用於執行查詢語句(一)首行首列
      public static int ExecuteScalar(string cmdtext, CommandType type, params SqlParameter[] parms)
      {
          using (SqlConnection conn = new SqlConnection(connstr))
          {
              conn.Open();
              using (SqlCommand comm = new SqlCommand(cmdtext, conn))
              {
                  comm.CommandType = type;
                  comm.Parameters.AddRange(parms);
                  return (int)comm.ExecuteScalar();
              }
          }
      
      }
      //用於執行查詢語句(二)一條一條讀取
      static public SqlDataReader ExecuteDataReader(string cmdText, CommandType type, params SqlParameter[] parms)
      {
          SqlConnection conn = new SqlConnection(connstr);
          conn.Open();
          using (SqlCommand cmd = new SqlCommand(cmdText,conn))
          {
              cmd.Parameters.AddRange(parms);
            
              cmd.CommandType = type;

              return cmd.ExecuteReader(CommandBehavior.CloseConnection);
          }
      }

      //用於執行查詢語句(三)全部讀取
      static public DataTable ExecuteTable(string cmdText, CommandType ctype, params SqlParameter[] parms)
      {
          using (SqlConnection conn = new SqlConnection(connstr))
          {
              conn.Open();
              using (SqlDataAdapter sda = new SqlDataAdapter(cmdText, conn))
              {
                  sda.SelectCommand.Parameters.AddRange(parms);

                  DataTable dt = new DataTable();

                  sda.Fill(dt);

                  return dt;
              }
          }
      }

     
    }
}

 

TDal層

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using System.Data;
using System.Data.SqlClient;



namespace DAL
{
 public  class Tdal
    {
     public int ADD(Tmodel model)
     {  //添加語句(注冊)
         string sqltext = "insert into Text(Id,Pname,Pwd,Pheight,Pgender,Paddress,Pbirthday) values(@id,@pname,@pwd,@pheight,@gender,@paddress,@pbirthday)";
         SqlParameter[] parms = { new SqlParameter("@id",model.Id),
                                  new SqlParameter("@pname",model.Pname),
                                  new SqlParameter("@pwd",model.Pwd),
                                  new SqlParameter("@pheight",model.Pheight),
                                  new SqlParameter("@gender",model.Pgender),
                                  new SqlParameter("@paddress",model.Padderss),
                                  new SqlParameter("@pbirthday",model.Pbirthday)                  
                                };
         return DBHerper.ExecuteNunQuery(sqltext,CommandType.Text,parms);
     }

     //查詢語句(登錄)
     public int LoginByName(string name,string pwd)
     {
         string sqltext = "select count(*) from Text where pname=@name,pwd=@pwd";
         SqlParameter[] parms = { new SqlParameter("@name", name),
                                 new  SqlParameter("@pwd", pwd) };
         return DBHerper.ExecuteScalar(sqltext,CommandType.Text,parms);
     }

     //刪除語句(刪除)
     public int DeleteId(Guid id)
     {
         string sqltext = "delete  from Text where Id=@id";
         SqlParameter parms = new SqlParameter("@id",id);
         return DBHerper.ExecuteNunQuery(sqltext,CommandType.Text,parms);
     }

     //查詢語句(讀取信息)
     public DataTable SelecteByName()
     {
         string sqltext = "select * from Text";
         return DBHerper.ExecuteTable(sqltext,CommandType.Text);
     }

     //修改語句(先查詢)
     public SqlDataReader SUpdate(Guid id)
     {
         string sqlse = "select * from Text where Id=@id";
         SqlParameter parms = new SqlParameter("@id",id);
         return DBHerper.ExecuteDataReader(sqlse,CommandType.Text,parms);  
     }

     //修改語句(后修改)
     public int Update(Tmodel model)
     {    
         string sqlxg = "update  Text set Pname=@name,Pwd=@pwd,Pheight=@height,Pgender=@gender,Paddress=@address,pbirthday=@birthday where Id=@id";
         SqlParameter[] parms = {
                                 
                                  new SqlParameter("@name",model.Pname),
                                  new SqlParameter("@pwd",model.Pwd),
                                  new SqlParameter("@height",model.Pheight),
                                  new SqlParameter("@gender",model.Pgender),
                                  new SqlParameter("@address",model.Padderss),
                                  new SqlParameter("@birthday",model.Pbirthday),
                                  new SqlParameter("@id",model.Id)
                                };
         return DBHerper.ExecuteNunQuery(sqlxg,CommandType.Text,parms);
     
     }
 }
}

 

 TBLL層

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using Model;
using System.Data;
using System.Data.SqlClient;



namespace BLL
{
  public   class Tbll
    {
      Tdal dal = new Tdal();
      public bool ADD(Tmodel model)  //添加
      {
          if (dal.ADD(model)>0)
          {
              return true;
          }
          else
          {
              return false;
          }
      
      }
      public bool LoginByName(string name, string pwd) //通過用戶名查詢
      {
          if (dal.LoginByName(name,pwd)>0)
          {
              return true;
          }
          else
          {
              return false;
          }
      }

      public bool DeleteId(Guid id) //刪除 
      {
          if (dal.DeleteId(id)>0)
          {
              return true;
          }
          else
          {
              return false;
          }
      
      }

      public DataTable SelecteByName() //查詢語句
      {
          return dal.SelecteByName();
      } 

      public SqlDataReader SUpdate(Guid id) //先根據id查詢
     {
          return dal.SUpdate(id);
     }
      public int Update(Tmodel model)   //在修改
      {
          return dal.Update(model);
      }
  
  }
}

 

 UI層主界面

 

主要代碼(窗體加載數據,刪除數據):

using BLL;
using Model;
using System.Data.SqlClient;


namespace UI
{
    public partial class Select : Form
    {
        public Select()
        {
            InitializeComponent();
        }
        //實例化Tbll,Tmodel
        Tbll bll = new Tbll(); 
        Tmodel model = new Tmodel();

        private void Select_Load(object sender, EventArgs e)//窗體加載事件
        {  
            //加載所有的數據
            DataTable dt = bll.SelecteByName();//調用bll層里的SelecteByName方法
            foreach (DataRow item in dt.Rows)
            {
                string format = string.Format("{0},{1},{2},{3},{4},{5},{6}", item[0], item[1], item[2], item[3], item[4], item[5], item[6]);
                listBox1.Items.Add(format);
            }
        }

        private void button3_Click(object sender, EventArgs e)  //增加按鈕事件
        {
            //注冊窗體
            Regist r = new Regist();
            r.Show();
            this.Hide();
        }

        private void button1_Click(object sender, EventArgs e)  //刪除按鈕的單擊事件
        {
            
            string  seid =listBox1.Items[0].ToString();//獲取選中的項
            string[] str = seid.Split(','); //分割
            string ids = str[0]; 
            Guid idid = Guid.Parse(ids);
            if (bll.DeleteId(idid))   //根據ID刪除
            {
                MessageBox.Show("刪除成功!");
                Select s = new Select();
                s.Show();
                this.Hide();
                
            }
            else
            {
                MessageBox.Show("刪除失敗!");
            }
        }

        private void button2_Click(object sender, EventArgs e) //修改按鈕事件
        {
            string ss = listBox1.SelectedItem.ToString();
            string[] str = ss.Split(',');
            string ids = str[0];
            Guid idid = Guid.Parse(ids);//選中列表的項
            SqlDataReader sda=bll.SUpdate(idid);
            if (sda.Read())
            {
                //從sda獲取各項值
                string  name = sda[1].ToString();
                string  pwd = sda[2].ToString();
                int     height = Convert.ToInt32(sda[3]);
                bool    gender = Convert.ToBoolean(sda[4]);
                string  address = sda[5].ToString();
                DateTime birthday = Convert.ToDateTime(sda[6]);
                Updates  up = new Updates(idid,name,pwd,height,gender,address,birthday);//將sda中的值使用構造函數傳參
                up.Show();
                this.Hide();
            }
            else
            {
                MessageBox.Show("傳參失敗!");
            }
        }
        private void button4_Click(object sender, EventArgs e) //查詢按鈕事件
        {   //登錄窗體
            Login l = new Login();
            l.Show();
            this.Hide();
        }
    }
}

 

 窗體加載運行效果:

 

刪除效果:

 

 

增加事件(注冊)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Model;
using BLL;
using System.Security.Cryptography;

namespace UI
{
    public partial class Regist : Form
    {
        public Regist()
        {
            InitializeComponent();
        }
    
        Tbll bll = new Tbll();
        Tmodel model = new Tmodel();
        private void button1_Click(object sender, EventArgs e) //注冊按鈕事件
        {  //定義變量
            Guid id = Guid.NewGuid();
            string name = this.txtname.Text.Trim();
            string pwd = this.txtpwd.Text.Trim();       
            int heighter = Convert.ToInt32( this.txtheight.Text.Trim());
            string birthday = this.dateTimePicker1.Text.Trim();
            string address = this.txtaddress.Text.Trim();
            bool gender = this.rbman.Checked ? true : false;  

            //判斷是否為空
            if (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(pwd))
            {
                MessageBox.Show("用戶名和密碼不能為空!");
                return;
            }
            else
            {
                model.Id = id;
                model.Pname = name;
                //為密碼進行MD5加密
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] bytes = Encoding.Default.GetBytes(pwd);
                byte[] bste = md5.ComputeHash(bytes);
                pwd = BitConverter.ToString(bste).Replace("-", "");

                model.Padderss = address;
                model.Pgender = gender;
                model.Pbirthday = Convert.ToDateTime(birthday);
                model.Pheight = heighter;
                model.Pwd = pwd;
                if (bll.ADD(model))
                {
                    MessageBox.Show("注冊成功");
                }
                else
                {
                    MessageBox.Show("注冊失敗!");
                }
            }

        }

        private void button2_Click(object sender, EventArgs e) //返回按鈕事件
        {
            Select s = new Select();
            s.Show();
            this.Hide();
        }
    }
}

 

 運行效果:

 

修改事件代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Model;
using BLL;


namespace UI
{
    public partial class Updates : Form
    {
        Tmodel model = new Tmodel();
        Tbll bll = new Tbll();
        string idid  = string.Empty;
        public Updates(Guid id,string name,string pwd,int height,bool gender,string address,DateTime birthday)
        {
            InitializeComponent();
            this.idid=id.ToString();            
            this.txtname.Text=name;
            this.txtpwd.Text = pwd;
            this.txtheight.Text = Convert.ToString(height);
            this.txtaddress.Text = address;
            this.dateTimePicker1.Text = birthday.ToString(); ;
            gender = this.rbman.Checked ? true : false;
                  
        }
        private void button1_Click(object sender, EventArgs e) //保存事件
        {   //定義變量獲取值
            string name = this.txtname.Text.Trim();
            string pwd = this.txtpwd.Text.Trim();
            int height = Convert.ToInt32(this.txtheight.Text.Trim());
            string address = this.txtaddress.Text.Trim();
            DateTime birthday = Convert.ToDateTime(this.dateTimePicker1.Text.Trim());
            bool gender = this.rbman.Checked ? true : false;
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(pwd))
            {
                model.Id = Guid.Parse(idid);
                model.Pname = name;
                model.Pwd = pwd;
                model.Pheight = height;
                model.Pgender = gender;
                model.Padderss = address;
                model.Pbirthday = birthday;
                if (bll.Update(model) > 0)
                {
                    MessageBox.Show("修改成功!");
                }
                else
                {
                    MessageBox.Show("修改失敗!");
                }
            }
        } 
        private void button2_Click(object sender, EventArgs e)
        {
            Select s = new Select();
            s.Show();
            this.Hide();
        }
    }
}

 

運行結果:

 

 

 

 查詢事件(登錄)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Model;
using BLL;
using System.Security.Cryptography;

namespace UI
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }
        Tmodel model = new Tmodel();
        Tbll bll = new Tbll();

        private void btnlogin_Click(object sender, EventArgs e) //登錄按鈕事件
        {    
            string name = this.textBox1.Text.Trim();
            string pwd = this.textBox2.Text.Trim();
       
            if (!string.IsNullOrEmpty(name)&& !string.IsNullOrEmpty(pwd))
            {
                model.Pname = name;

                #region 加密
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] bytes = Encoding.Default.GetBytes(pwd);
                byte[] bste = md5.ComputeHash(bytes);
                pwd = BitConverter.ToString(bste).Replace("-", "");
                #endregion

                model.Pwd = pwd;
                MessageBox.Show("登陸成功!");
                Select s = new Select();
                s.Show();
                this.Hide();
            }
            else
            {
                MessageBox.Show("用戶名和密碼不能為空!");
            }
        }

        private void btnre_Click(object sender, EventArgs e)//跳轉到注冊頁面
        {
            Regist r = new Regist();
            r.Show();
            this.Hide();
        }

        private void button1_Click(object sender, EventArgs e)//跳轉到主界面
        {
            Select s = new Select();
            s.Show();
            this.Hide();
        }
    }
}

 

運行結果:

 

 

  三層架構終於寫完了,在寫的過程中,發現還是有很多地方不太熟練,所以還得要多加練習。。。接下來的幾天將會學習並總結JavaScript。。。呵呵,繼續加油了!O(∩_∩)O....不管我寫的好不好,我都會微笑面對,勇敢的走下去!加油!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM