【C#】简单三层架构(MVC)实现学生信息管理

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_41138935/article/details/84981123

一个简单的demo,代码不多,适合初学者。

三层架构分别是:表示层(UI)、业务逻辑层(NLL)、数据访问层(DAL).

视频讲解教程:

微课7-1三层架构的搭建-----https://2d.hep.com.cn/47486/98

微课7-2显示学生信息--------https://2d.hep.com.cn/47486/99

微课7-3添加学生信息--------https://2d.hep.com.cn/47486/100

微课7-4修改学生信息--------https://2d.hep.com.cn/47486/101

微课7-5删除学生信息--------https://2d.hep.com.cn/47486/102

源代码下载地址:  https://www.lanzous.com/i2lfucf

注意:

1.数据库在TriStu\bin\debug目录下

2.需要在DBHelper改数据库连接字符串


一、数据库(StuDB)

        数据库表的名称

             表名:T_Stu

        数据库表的结构及数据

             

二、项目概览

       1.总体图

TriStu---表示层

TriStu.BLL---业务逻辑层

TriStu.DAL---数据访问层

TriStu.Models---实体类

     2.软件运行截图

三:实现代码

1.Form1.cs

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 TriStu.BLL;
using TriStu.Models;

namespace TriStu
{
    public partial class Form1 : Form
    {
        StuManager stu=new StuManager();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = stu.GetStudentList();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Student newStu = new Student();
            newStu.ID = int.Parse(txtID.Text);
            newStu.Name = txtName.Text;
            newStu.Age = int.Parse(txtAge.Text);
            if (stu.AddStudent(newStu))
            {
                MessageBox.Show("添加成功");
                dataGridView1.DataSource = stu.GetStudentList();
            }
            else
            {
                MessageBox.Show("添加失败");
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //判断是否选中dataGridView1里的一行
            if (dataGridView1.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择一行进行操作");
                return;
            }
            txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
            txtName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
            txtAge.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
             //判断是否选中dataGridView1里的一行
             if (dataGridView1.SelectedRows.Count <= 0)
             {
                MessageBox.Show("请选择一行进行操作");
                return;
             }
            Student newStu = new Student();
            newStu.ID = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
            newStu.Name = txtName.Text;
            newStu.Age = int.Parse(txtAge.Text);

            //保存修改
            if (stu.UpdateStudent(newStu))
            {
                MessageBox.Show("修改成功");
                dataGridView1.DataSource = stu.GetStudentList();
            }
            else
            {
                MessageBox.Show("修改失败");
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            int id;
            if (dataGridView1.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选中一行进行操作");
                return;
            }
            id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
            //删除
            if (stu.DelStudent(id))
            {
                MessageBox.Show("删除成功");
                dataGridView1.DataSource = stu.GetStudentList();
                txtID.Text = "";
                txtName.Text = "";       
                txtAge.Text = "";
            }
            else
            {
                MessageBox.Show("删除失败");
            }
        }
    }
}

2.StuManager.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TriStu.DAL;
using TriStu.Models;

namespace TriStu.BLL
{
    public class StuManager
    {
        StuService stu = new StuService();
        public List<Student> GetStudentList()
        {
            return stu.GetStudentList();
        }
        #region 添加学生
        /// <summary>
        /// 添加学生
        /// </summary>
        /// <param name="newStu">学生</param>
        /// <returns>返回bool值</returns>
        public bool AddStudent(Student newStu)
        {
            return stu.AddStudent(newStu);
        }
        #endregion
        #region 修改学生信息
        /// <summary>
        /// 修改学生信息
        /// </summary>
        /// <param name="s">学生</param>
        /// <returns>返回bool值</returns>
        public bool UpdateStudent(Student s)
        {
            return stu.UpdateStudent(s);
        }
        #endregion

        public bool DelStudent(int id)
        {
            return stu.DelStudent(id);
        }
    }
}

3.DBHelper.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;

namespace TriStu.DAL
{
    public class DBHelper
    {
        //数据库连接字符串--记得改
        public static string connString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\24040\source\repos\TriStu\TriStu\bin\Debug\StuDB.mdf;Integrated Security=True;Connect Timeout=30";
        //定义数据库连接对象
        public static SqlConnection conn = new SqlConnection(connString);

        #region 获取数据的方法
        /// <summary>
        /// 获取数据的方法
        /// </summary>
        /// <param name="sqlStr">select语句</param>
        /// <returns>返回DaraTable对象</returns>
        public static DataTable GetDataTable(string sqlStr)
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sqlStr, conn);
                SqlDataAdapter dapt = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                dapt.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                return null;
                //throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        #endregion
        #region 获取数据的重载方法
        /// <summary>
        /// 获取数据的重载方法
        /// </summary>
        /// <param name="sqlStr">select语句</param>
        /// <param name="param">SqlParameter对象数组</param>
        /// <returns>返回DataTable对象</returns>
        public static DataTable GetDataTable(string sqlStr, SqlParameter[] param)
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sqlStr,conn);
                cmd.Parameters.AddRange(param);
                SqlDataAdapter dapt = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                dapt.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                return null;
                //throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        #endregion
        #region 执行更新方法
        /// <summary>
        /// 执行更新方法
        /// </summary>
        /// <param name="sqlStr">insert|update|delete语句</param>
        /// <returns>返回一个bool值</returns>
        public static bool ExcuteCommand(string sqlStr)
        {
            try
            {
                //conn.Open();
                SqlCommand cmd = new SqlCommand(sqlStr, conn);
                conn.Open();
                cmd.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                return false;
                //throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        #endregion
        #region 执行更新的重载方法
        /// <summary>
        /// 执行更新的重载方法
        /// </summary>
        /// <param name="sqlStr">insert|update|delete语句</param>
        /// <param name="param">SqlParameter对象数组</param>
        /// <returns>返回一个bool值</returns>
        public static bool ExcuteCommand(string sqlStr, SqlParameter[] param)
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sqlStr, conn);
                cmd.Parameters.AddRange(param);
                cmd.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                return false;
                //throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        #endregion

        public static bool ExcuteCommand(List<String> sqlStr, List<SqlParameter[]> param)
        {
            int i = 0;
            SqlCommand cmd = new SqlCommand();
            using (TransactionScope ts = new TransactionScope())
            {
                cmd.Connection = conn;
                conn.Open();
                try
                {
                    foreach (string item in sqlStr)
                    {
                        //设置命令类型为SQL文本命令
                        cmd.CommandType = CommandType.Text;
                        //设置对数据源执行的SQL语句
                        cmd.CommandText = item;
                        //添加参数
                        cmd.Parameters.AddRange(param[i]);
                        //执行SQL语句并返回受影响的行数
                        cmd.ExecuteNonQuery();
                        i++;
                    }
                    ts.Complete();
                    return true;
                }
                catch(Exception ex)
                {
                    throw ex;
                    return false;
                }
                finally
                {
                    conn.Close();
                    sqlStr.Clear();
                }
            }
        }
    }
}

4.StuService.cs

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

namespace TriStu.DAL
{
    public class StuService
    {
        public List<Student> GetStudentList()
        {
            string sqlstr = "select * from T_Stu";
            DataTable dt = DBHelper.GetDataTable(sqlstr);
            List<Student> list = new List<Student>();
            foreach(DataRow r in dt.Rows)
            {
                Student stu = new Student();
                stu.ID = int.Parse(r["ID"].ToString());
                stu.Name = r["name"].ToString();
                stu.Age = int.Parse(r["age"].ToString());
                list.Add(stu);
            }
            return list;
        }
        #region 添加学生信息
        /// <summary>
        /// 添加学生信息
        /// </summary>
        /// <param name="newStu">学生</param>
        /// <returns>返回bool值</returns>
        public bool AddStudent(Student newStu)
        {
            string sqlStr = "insert into T_Stu values(@ID,@name,@age)";
            SqlParameter[] param = new SqlParameter[]
            {
                new SqlParameter("@ID",newStu.ID),
                new SqlParameter("@name",newStu.Name),
                new SqlParameter("@age",newStu.Age)
            };
            return DBHelper.ExcuteCommand(sqlStr, param);
        }
        #endregion
        #region 修改学生信息
        /// <summary>
        /// 修改学生信息
        /// </summary>
        /// <param name="stu">学生</param>
        /// <returns>返回bool值</returns>
        public bool UpdateStudent(Student stu)
        {
            string sqlstr = "update T_Stu set name=@name,age=@age where ID=@id";
            SqlParameter[] param = new SqlParameter[]
            {
                new SqlParameter("@ID",stu.ID),
                new SqlParameter("@name",stu.Name),
                new SqlParameter("@age",stu.Age)
            };
            return DBHelper.ExcuteCommand(sqlstr, param);
        }
        #endregion
        public bool DelStudent(int id)
        {
            List<String> strSqls = new List<string>();
            List<SqlParameter[]> param = new List<SqlParameter[]>();
            string strDeletel = "DELETE from T_Stu where ID=@id";

            strSqls.Add(strDeletel);
            SqlParameter[] param1 = new SqlParameter[]
            {
                new SqlParameter("@ID",id)
            };
            param.Add(param1);

            //新增的未加入到T_Sc表,这里不删除这个表的数据
            //string strDelete2 = "DELETE from T_Stu where Sno=@sno";
            //strSqls.Add(strDelete2);
            //SqlParameter[] param2 = new SqlParameter[]
            //{
            //    new SqlParameter("@sno",id)
            //};
            //param.Add(param2);

            return DBHelper.ExcuteCommand(strSqls, param);
        }
    }
}

5.Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TriStu.Models
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public Student(){}
        #region 构造方法
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="ID">ID</param>
        /// <param name="name">姓名</param>
        /// <param name="age">年龄</param>
        public Student(int ID, string name, int age)
        {
            this.ID = ID;
            this.Name = Name;
            this.Age = Age;
        } 
        #endregion
    }
}

 

展开阅读全文

没有更多推荐了,返回首页