框架一览
先来看看C#和SQL Server的整个框架
C#
SQL Server2019
数据库信息:
服务器:.
登录用户:sa
密码:123
数据库:Architecture_demo
表名:Student
清楚了框架那么就开始编写C#部分的程序。
C#程序编写
编写程序用的是Visual Studio 2019.
创建项目
BLL、DAL、Model为".dll类库"项目,UI为"Windows窗体应用程序"项目。
Model实体模型搭建
在Model项目里创建Students类,且Students要为public,
C#中的Students类与数据库中的Student的表,是多了一个“s”的,用于区分,
这里的属性要与数据库中的Student表要一样。
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceModel{ publicclassStudents { publicintstudent_ID { get; set; } publicstringname { get; set; } publicintage { get; set; } publicstringgender { get; set; } } }
DAL数据访问层
首先在UI项目里的App.config文件中添加一段代码,在数据库服务器名称和密码发生改变时,不用修改程序代码,只需要修改App.config文件中这段代码既可
Server:数据库服务器的名称 DataBase:数据库名称
Uid:用户名 Pwd:密码
<connectionStrings><addname="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的操作
以下是代码:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Data; usingSystem.Data.SqlClient; usingSystem.Configuration; namespaceDAL{ publicclassSQLHelper { privatestaticreadonlystringconnString=ConfigurationManager.ConnectionStrings["connString"].ToString(); /// <summary>/// 对数据库进行增删改/// </summary>/// <param name="sql">要查询的SQL语句</param>/// <returns>返回受影响的行数</returns>publicstaticintUpdate(stringsql) { //与数据库连接的字符串SqlConnectionconn=newSqlConnection(connString); //SQL语句SqlCommandcmd=newSqlCommand(sql, conn); try { //与数据库建立连接conn.Open(); returncmd.ExecuteNonQuery(); } catch (Exceptionex) { throwex; } finally { //断开与数据库的连接conn.Close(); } } /// <summary>/// 执行单一结果查询/// </summary>/// <param name="sql">要查询的SQL语句</param>/// <returns>返回单一的查询结果</returns>publicstaticobjectGetSingleResult(stringsql) { SqlConnectionconn=newSqlConnection(connString); SqlCommandcmd=newSqlCommand(sql, conn); try { conn.Open(); returncmd.ExecuteScalar(); } catch (Exceptionex) { throwex; } finally { conn.Close(); } } /// <summary>/// 执行一个结果集的查询/// </summary>/// <param name="sql">要查询的SQL语句</param>/// <returns>返回一个SqlDataReader对象</returns>publicstaticSqlDataReaderGetReader(stringsql) { SqlConnectionconn=newSqlConnection(connString); SqlCommandcmd=newSqlCommand(sql, conn); try { conn.Open(); SqlDataReaderobjReader=cmd.ExecuteReader(CommandBehavior.CloseConnection); returnobjReader; } catch (Exceptionex) { throwex; } } } }
BLL业务逻辑层
在BLL里创建StudentService类,StudentService要为public
引入DAL、Model
接着在StudentService类的代码里引入
System.Data、System.Data.SqlClient
以下是代码:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Data; usingSystem.Data.SqlClient; usingDAL; usingModel; namespaceBLL{ publicclassStudentService { /// <summary>/// 增加一条数据/// </summary>/// <param name="objStudent"></param>/// <returns></returns>publicintAddStudent(StudentsobjStudent) { //【1】编写sql语句StringBuildersqlBuilder=newStringBuilder("insert into Student "); sqlBuilder.Append(" (name,age,gender) "); sqlBuilder.Append(" values('{0}',{1},'{2}');select @@identity "); //【2】解析对象stringsql=string.Format(sqlBuilder.ToString(), objStudent.name,objStudent.age,objStudent.gender); //【3】提交SQL语句try { returnConvert.ToInt32(SQLHelper.GetSingleResult(sql));//执行sql语句,返回学号 } catch (Exceptionex) { thrownewException("添加学员时数据访问异常:"+ex.Message); } } /// <summary>/// 删除一条数据/// </summary>/// <param name="studentId"></param>/// <returns></returns>publicintDeleteStudent(stringstudentId) { stringsql="delete from Student where Student_ID="+studentId; try { returnSQLHelper.Update(sql); } catch (SqlExceptionex) { //547是数据库返回的消息,返回改该消息表示不能被删除if (ex.Number==547) { thrownewException("该学号被其他实体引用,不能直接删除该学员对象!"); } else { thrownewException("删除学员对象发生数据异常!"+ex.Message); } } catch (Exceptionex) { throwex; } } /// <summary>/// 修改学生信息/// </summary>/// <param name="objStudent"></param>/// <returns></returns>publicintModifyStudent(StudentsobjStudent) { StringBuildersqlBuilder=newStringBuilder(); sqlBuilder.Append("update Student set name='{0}',age={1},gender='{2}' "); stringsql=string.Format(sqlBuilder.ToString(), objStudent.name,objStudent.age,objStudent.gender); try { returnSQLHelper.Update(sql); } catch (Exceptionex) { thrownewException("修改学员信息是数据访问发生异常:"+ex.Message); } } /// <summary>/// 根据学号查询学生/// </summary>/// <param name="studentId"></param>/// <returns></returns>publicStudentsGetStudentById(stringstudentId) { stringsql="select Student_ID,name,age,gender from Student "; sql+=" where Student_ID="+studentId; SqlDataReaderobjReader=SQLHelper.GetReader(sql); StudentsobjStudent=null; if (objReader.Read()) { objStudent=newStudents() { student_ID=Convert.ToInt32(objReader["student_ID"]), name=objReader["name"].ToString(), age=Convert.ToInt32(objReader["age"]), gender=objReader["gender"].ToString() }; } objReader.Close(); returnobjStudent; } } }
UI表现层
在工具箱找到TabControl,拖动到窗口
增加两个页面,第一个为“增”,第二个为“删、改、查”
“增”界面
这里说明一下因为学号在数据库里面是主键,是不能更改的,但是在添加其他数据的时候,学号是会自增数据的,每一条数据+1,这个每次增加的数可以在数据库里面修改的
“删、改、查”界面
UI代码
首先在UI项目里引入DAL、BLL、Model
“增”界面代码
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Windows.Forms; usingDAL; usingBLL; usingModel; namespaceUI{ publicpartialclassForm1 : Form { privateStudentServiceobjStudentService=newStudentService(); List<Students>stuList=newList<Students>();//用来临时保存学员对象publicForm1() { InitializeComponent(); } /// <summary>/// 添加按钮/// </summary>/// <param name="sender"></param>/// <param name="e"></param>privatevoidbtn_Add_Click(objectsender, EventArgse) { //封装学生对象StudentsojbStudent=newStudents() { name=this.txt_Z_name.Text.Trim(), age=Convert.ToInt32(this.txt_Z_age.Text.Trim()), gender=this.rdoMale.Checked?"男" : "女" }; //调用后台数据访问方法intstudentId=objStudentService.AddStudent(ojbStudent); try { //同步显示添加的学员ojbStudent.student_ID=studentId; this.stuList.Add(ojbStudent); this.dgvStudentList.DataSource=null; this.dgvStudentList.DataSource=this.stuList; //询问是否继续添加DialogResultresult=MessageBox.Show("新学员添加成功!是否继续添加?", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result==DialogResult.Yes) { //清空用户输入的信息foreach (Controliteminthis.gbstuinfo.Controls) { if (itemisTextBox) { item.Text=""; } elseif (itemisRadioButton) { ((RadioButton)item).Checked=false; } } } } catch (Exceptionex) { MessageBox.Show("添加学员出现数据访问异常"+ex.Message); } } } }
UI全部代码
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Windows.Forms; usingDAL; usingBLL; usingModel; namespaceUI{ publicpartialclassForm1 : Form { privateStudentServiceobjStudentService=newStudentService(); List<Students>stuList=newList<Students>();//用来临时保存学员对象publicForm1() { InitializeComponent(); } /// <summary>/// 添加按钮/// </summary>/// <param name="sender"></param>/// <param name="e"></param>privatevoidbtn_Add_Click(objectsender, EventArgse) { //封装学生对象StudentsojbStudent=newStudents() { name=this.txt_Z_name.Text.Trim(), age=Convert.ToInt32(this.txt_Z_age.Text.Trim()), gender=this.rdoMale.Checked?"男" : "女" }; //调用后台数据访问方法intstudentId=objStudentService.AddStudent(ojbStudent); try { //同步显示添加的学员ojbStudent.student_ID=studentId; this.stuList.Add(ojbStudent); this.dgvStudentList.DataSource=null; this.dgvStudentList.DataSource=this.stuList; //询问是否继续添加DialogResultresult=MessageBox.Show("新学员添加成功!是否继续添加?", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result==DialogResult.Yes) { //清空用户输入的信息//gbstuinfo是“增”界面的“基本信息”框,也就是工具箱的GroupBox控件foreach (Controliteminthis.gbstuinfo.Controls) { if (itemisTextBox) { item.Text=""; } elseif (itemisRadioButton) { ((RadioButton)item).Checked=false; } } } } catch (Exceptionex) { MessageBox.Show("添加学员出现数据访问异常"+ex.Message); } } /// <summary>/// 查询按钮/// </summary>/// <param name="sender"></param>/// <param name="e"></param>privatevoidbtn_Inquire_Click(objectsender, EventArgse) { if (this.txt_S_StudentId.Text.Length==0) { MessageBox.Show("请输入学号!", "查询提示!"); return; } StudentsobjStudent=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>privatevoidbtn_Edit_Click(objectsender, EventArgse) { 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; } //封装学员对象StudentsobjStudent=newStudents() { 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 (Exceptionex) { MessageBox.Show(ex.Message, "提示信息"); } } privatevoiddgvStudentList2_CellClick(objectsender, DataGridViewCellEventArgse) { 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; } } //删除privatevoidbtn_Delete_Click(objectsender, EventArgse) { if (this.dgvStudentList2.RowCount==0) { MessageBox.Show("没有任何需要删除的学员!", "提示信息"); return; } if (this.dgvStudentList2.CurrentRow==null) { MessageBox.Show("请先选中要删除的学员!", "提示信息"); return; } //删除前的确认DialogResultresult=MessageBox.Show("确认删除吗!", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (result==DialogResult.Cancel) return; //获取学号stringstudentId=this.dgvStudentList2.CurrentRow.Cells["Student_ID"].Value.ToString(); try { objStudentService.DeleteStudent(studentId); dgvStudentList2.DataSource=null; } catch (Exceptionex) { MessageBox.Show(ex.Message, "提示信息"); } } } }
提示:表格的名字和数据名要与数据库的字段对应
演示视频
B站:https://www.bilibili.com/video/BV1Mr4y1X74a/