C#&SQL Server基于三层架构实现增删改查
C # SQL Server implement CRUD-based three-tier architecture
先来看看C#和SQL Server的整个框架
C#
SQL Server
这是本次使用到数据库的一些信息
服务器名称:DESKTOP-D258CHD\WINCC
登录用户:sa 密码:123
数据库:Architecture_demo 表名:Student
清楚了框架那么现在开始编写C#部分的程序
1_首先创建以下四个项目
BLL、DAL、Model为".dll类库"项目,UI为"Windows窗体应用程序"项目
2_Model实体模型搭建
创建Students类,且Students要为public
C#中的Students类与数据库中的Student的表,是多了一个“s”的,用于区分
这里的属性要与数据库中的Student表要一样
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Model{public class Students{public int student_ID { get; set; }public string name { get; set; }public int age { get; set; }public string gender { get; set; }}}
3_DAL数据访问层
首先在UI项目里的App.config文件中添加一段代码,在数据库服务器名称和密码发生改变时,不用修改程序代码,只需要修改App.config文件中这段代码既可
Server:数据库服务器的名称 DataBase:数据库名称
Uid:用户名 Pwd:密码
<connectionStrings><add name="connString" connectionString="Server=DESKTOP-D258CHD\WINCC;DataBase=Architecture_demo;Uid=sa;Pwd=123" /></connectionStrings>
然后返回到DAL项目,在DAL项目引用里添加System.Configuration,用于读取UI项目的App.config文件
在DAL项目里创建SQLHelper类,SQLHelper要为public,同时引入System.Data、System.Data.SqlClient、System.Configuration
System.Data:提供对数据的操作
System.Data.SqlClient:提供对数据库的操作
System.Configuration:提供对App.config的操作
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{public class SQLHelper{}}
开始编写数据访问层代码
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{public class SQLHelper{private static readonly string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();/// <summary>/// 对数据库进行增删改/// </summary>/// <param name="sql">要查询的SQL语句</param>/// <returns>返回受影响的行数</returns>public static int Update(string sql){//与数据库连接的字符串SqlConnection conn = new SqlConnection(connString);//SQL语句SqlCommand cmd = new SqlCommand(sql, conn);try{//与数据库建立连接conn.Open();return cmd.ExecuteNonQuery();}catch (Exception ex){throw ex;}finally{//断开与数据库的连接conn.Close();}}/// <summary>/// 执行单一结果查询/// </summary>/// <param name="sql">要查询的SQL语句</param>/// <returns>返回单一的查询结果</returns>public static object GetSingleResult(string sql){SqlConnection conn = new SqlConnection(connString);SqlCommand cmd = new SqlCommand(sql, conn);try{conn.Open();return cmd.ExecuteScalar();}catch (Exception ex){throw ex;}finally{conn.Close();}}/// <summary>/// 执行一个结果集的查询/// </summary>/// <param name="sql">要查询的SQL语句</param>/// <returns>返回一个SqlDataReader对象</returns>public static SqlDataReader GetReader(string sql){SqlConnection conn = new SqlConnection(connString);SqlCommand cmd = new SqlCommand(sql, conn);try{conn.Open();SqlDataReader objReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);return objReader;}catch (Exception ex){throw ex;}}}}
4_BLL业务逻辑层
在BLL里创建StudentService类,StudentService要为public
引入DAL、Model
接着在StudentService类的代码里引入
System.Data、System.Data.SqlClient
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data;using System.Data.SqlClient;using DAL;using Model;namespace BLL{public class StudentService{}}
开始编写业务逻辑层代码
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data;using System.Data.SqlClient;using DAL;using Model;namespace BLL{public class StudentService{/// <summary>/// 增加一条数据/// </summary>/// <param name="objStudent"></param>/// <returns></returns>public int AddStudent(Students objStudent){//【1】编写sql语句StringBuilder sqlBuilder = new StringBuilder("insert into Student ");sqlBuilder.Append(" (name,age,gender) ");sqlBuilder.Append(" values('{0}',{1},'{2}');select @@identity ");//【2】解析对象string sql = string.Format(sqlBuilder.ToString(), objStudent.name,objStudent.age,objStudent.gender);//【3】提交SQL语句try{return Convert.ToInt32(SQLHelper.GetSingleResult(sql));//执行sql语句,返回学号}catch (Exception ex){throw new Exception("添加学员时数据访问异常:" + ex.Message);}}/// <summary>/// 删除一条数据/// </summary>/// <param name="studentId"></param>/// <returns></returns>public int DeleteStudent(string studentId){string sql = "delete from Student where Student_ID=" + studentId;try{return SQLHelper.Update(sql);}catch (SqlException ex){//547是数据库返回的消息,返回改该消息表示不能被删除if (ex.Number == 547){throw new Exception("该学号被其他实体引用,不能直接删除该学员对象!");}else{throw new Exception("删除学员对象发生数据异常!" + ex.Message);}}catch (Exception ex){throw ex;}}/// <summary>/// 修改学生信息/// </summary>/// <param name="objStudent"></param>/// <returns></returns>public int ModifyStudent(Students objStudent){StringBuilder sqlBuilder = new StringBuilder();sqlBuilder.Append("update Student set name='{0}',age={1},gender='{2}' ");string sql = string.Format(sqlBuilder.ToString(), objStudent.name,objStudent.age,objStudent.gender);try{return SQLHelper.Update(sql);}catch (Exception ex){throw new Exception("修改学员信息是数据访问发生异常:" + ex.Message);}}/// <summary>/// 根据学号查询学生/// </summary>/// <param name="studentId"></param>/// <returns></returns>public Students GetStudentById(string studentId){string sql = "select Student_ID,name,age,gender from Student ";sql += " where Student_ID=" + studentId;SqlDataReader objReader = SQLHelper.GetReader(sql);Students objStudent = null;if (objReader.Read()){objStudent = new Students(){student_ID=Convert.ToInt32(objReader["student_ID"]),name=objReader["name"].ToString(),age = Convert.ToInt32(objReader["age"]),gender=objReader["gender"].ToString()};}objReader.Close();return objStudent;}}}
5_UI表现层
在工具箱找到TabControl,拖动到窗口
增加两个页面,第一个为“增”,第二个为“删、改、查”,并且修改界面
“增”界面
这里说明一下因为学号在数据库里面是主键,是不能更改的,但是在添加其他数据的时候,学号是会自增数据的,每一条数据+1,这个每次增加的数可以在数据库里面修改的
“删、改、查”界面
引入DAL、BLL、Model
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 DAL;using BLL;using Model;namespace UI{public partial class Form1 : Form{public Form1(){InitializeComponent();}}}
开始编写UI表现层代码
“增”界面代码
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 DAL;using BLL;using Model;namespace UI{public partial class Form1 : Form{private StudentService objStudentService = new StudentService();List<Students> stuList = new List<Students>();//用来临时保存学员对象public Form1(){InitializeComponent();}/// <summary>/// 添加按钮/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_Add_Click(object sender, EventArgs e){//封装学生对象Students ojbStudent = new Students(){name = this.txt_Z_name.Text.Trim(),age = Convert.ToInt32(this.txt_Z_age.Text.Trim()),gender = this.rdoMale.Checked ? "男" : "女"};//调用后台数据访问方法int studentId = objStudentService.AddStudent(ojbStudent);try{//同步显示添加的学员ojbStudent.student_ID = studentId;this.stuList.Add(ojbStudent);this.dgvStudentList.DataSource = null;this.dgvStudentList.DataSource = this.stuList;//询问是否继续添加DialogResult result = MessageBox.Show("新学员添加成功!是否继续添加?", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question);if (result == DialogResult.Yes){//清空用户输入的信息foreach (Control item in this.gbstuinfo.Controls){if (item is TextBox){item.Text = "";}else if (item is RadioButton){((RadioButton)item).Checked = false;}}}}catch (Exception ex){MessageBox.Show("添加学员出现数据访问异常" + ex.Message);}}}}
“删、改、查”界面代码,和“增”界面的一起,这里就是UI全部的代码
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 DAL;using BLL;using Model;namespace UI{public partial class Form1 : Form{private StudentService objStudentService = new StudentService();List<Students> stuList = new List<Students>();//用来临时保存学员对象public Form1(){InitializeComponent();}/// <summary>/// 添加按钮/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_Add_Click(object sender, EventArgs e){//封装学生对象Students ojbStudent = new Students(){name = this.txt_Z_name.Text.Trim(),age = Convert.ToInt32(this.txt_Z_age.Text.Trim()),gender = this.rdoMale.Checked ? "男" : "女"};//调用后台数据访问方法int studentId = objStudentService.AddStudent(ojbStudent);try{//同步显示添加的学员ojbStudent.student_ID = studentId;this.stuList.Add(ojbStudent);this.dgvStudentList.DataSource = null;this.dgvStudentList.DataSource = this.stuList;//询问是否继续添加DialogResult result = MessageBox.Show("新学员添加成功!是否继续添加?", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question);if (result == DialogResult.Yes){//清空用户输入的信息foreach (Control item in this.gbstuinfo.Controls){if (item is TextBox){item.Text = "";}else if (item is RadioButton){((RadioButton)item).Checked = false;}}}}catch (Exception ex){MessageBox.Show("添加学员出现数据访问异常" + ex.Message);}}/// <summary>/// 查询按钮/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_Inquire_Click(object sender, EventArgs e){if (this.txt_S_StudentId.Text.Length == 0){MessageBox.Show("请输入学号!", "查询提示!");return;}Students objStudent = objStudentService.GetStudentById(this.txt_S_StudentId.Text.Trim());this.stuList.Add(objStudent);this.dgvStudentList2.DataSource = null;this.dgvStudentList2.DataSource = this.stuList;}/// <summary>/// 修改按钮/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_Edit_Click(object sender, EventArgs e){if (txt_S_Id.Text == ""||txt_S_name.Text==""||txt_S_age.Text==""||rdo_S_Male.Checked==false&&rdo_S_Female.Checked==false){MessageBox.Show("数据不完整", "提示!");return;}//封装学员对象Students objStudent = new Students(){student_ID=Convert.ToInt32(this.txt_S_Id.Text.Trim()),name = this.txt_S_name.Text.Trim(),age=Convert.ToInt32(this.txt_S_age.Text.Trim()),gender=this.rdoMale.Checked ? "男" : "女"};try{if (objStudentService.ModifyStudent(objStudent) == 1){MessageBox.Show("学员信息修改成功!", "提示信息");}}catch (Exception ex){MessageBox.Show(ex.Message, "提示信息");}}private void dgvStudentList2_CellClick(object sender, DataGridViewCellEventArgs e){txt_S_Id.Text= this.dgvStudentList2.CurrentRow.Cells["Student_ID"].Value.ToString();txt_S_name.Text = this.dgvStudentList2.CurrentRow.Cells["name"].Value.ToString();txt_S_age.Text = this.dgvStudentList2.CurrentRow.Cells["age"].Value.ToString();if (this.dgvStudentList2.CurrentRow.Cells["gender"].Value.ToString() == "男"){rdo_S_Male.Checked = true;}else{rdo_S_Female.Checked = true;}}private void btn_Delete_Click(object sender, EventArgs e){if (this.dgvStudentList2.RowCount == 0){MessageBox.Show("没有任何需要删除的学员!", "提示信息");return;}if (this.dgvStudentList2.CurrentRow == null){MessageBox.Show("请先选中要删除的学员!", "提示信息");return;}//删除前的确认DialogResult result = MessageBox.Show("确认删除吗!", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);if (result == DialogResult.Cancel) return;//获取学号string studentId = this.dgvStudentList2.CurrentRow.Cells["Student_ID"].Value.ToString();try{objStudentService.DeleteStudent(studentId);dgvStudentList2.DataSource = null;}catch (Exception ex){MessageBox.Show(ex.Message, "提示信息");}}}}
提示:表格的名字和数据名要与数据库的字段对应
最后看下效果
2021/06/17
