• 三层架构


           ...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....不管我写的好不好,我都会微笑面对,勇敢的走下去!加油!

  • 相关阅读:
    kmp
    RMP
    p次方求和
    河南省之6 Metric Matrice
    表达式求值
    线段树
    办公软件试题
    河南省之6 遥控器
    三个水杯
    JLink + USBTO232 MINI作品
  • 原文地址:https://www.cnblogs.com/ysaw/p/4196387.html
Copyright © 2020-2023  润新知