【C#】簡單三層架構(MVC)實現學生資訊管理
阿新 • • 發佈:2019-01-12
一個簡單的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 [email protected],[email protected] where [email protected]";
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 [email protected]";
strSqls.Add(strDeletel);
SqlParameter[] param1 = new SqlParameter[]
{
new SqlParameter("@ID",id)
};
param.Add(param1);
//新增的未加入到T_Sc表,這裡不刪除這個表的資料
//string strDelete2 = "DELETE from T_Stu where [email protected]";
//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
}
}