三層架構之基礎篇(對數據庫增刪改查)


在上一篇中已經搭建好了一個三層架構的框架,現在使用三層架構來對數據庫進行增刪改查操作:

假設在數據庫ItcastCater有一張表ManagerInfo,有如下幾個字段

 

我們知道在UI,BLL,DAL之間有數據的交互,所以我們傳遞的數據需要有一個類型,因為我們操作的是ManagerInfo表,所以咱們可以在Model這里建一個類名為ManagerInfo的類,在這里定義的屬性需要和ManagerInfo表中的字段一一對應。我們知道DAL是處理和數據庫相關的操作,出了這個層就不在有和數據庫相關的代碼,所以我們需要封裝一個SqlHelper類,用於數據庫的操作。可以封裝成一個靜態類,作為工具類使用。同時,我們現在處理的是ManagerInfo這個表,以后也會操作其他的表,遵循單一原則,所以需要在DAL中建一個專門處理ManagerInfo表的類ManagerInfoDal,相應的在BLL中需要一個處理ManagerInfo表業務邏輯的類ManagerInfoBll。到這里所有的准備工作已經完成。(注意:我們使用的數據庫是SQLite,所以在數據庫操作那部分用的都是SQLite自帶的 類和對象)

1.查詢操作:

從最底層DAL開始寫起(SQLiteHelper):

 1 public static class SQLiteHelper
 2     {
 3         //連接字符串 
 4         static string strConn = ConfigurationManager.ConnectionStrings["Cater"].ConnectionString;
 5         #region 查詢數據 +DataTable GetList(string sql)
 6         /// <summary>
 7         /// 查詢數據
 8         /// </summary>
 9         /// <param name="sql">查詢字符串</param>
10         /// <returns></returns>
11         public static DataTable GetList(string sql)
12         {
13             //創建連接對象
14             using (SQLiteConnection conn = new SQLiteConnection(strConn))
15             {
16                 //創建橋接對象
17                 SQLiteDataAdapter adapter = new SQLiteDataAdapter(sql, conn);
18                 //創建表 對象
19                 DataTable table = new DataTable();
20                 //將數據 緩存到 表格中
21                 adapter.Fill(table);
22                 //返回數據
23                 return table;
24             }
25         } 
26         #endregion
27 }
查詢數據

 接着是ManagerInfoDal類中查詢代碼

 1 //由於出了DAL層就不允許有和數據庫相關的代碼,所以在這里返回的不是DataTable ,需要返回一個數據類型,在UI層接收時,使用面向對象來對數據進行操作
 2 public List<ManagerInfo> GetList()
 3 {
 4    DataTable table = SQLiteHelper.GetList("select * from managerinfo");
 5             List<ManagerInfo> list = new List<ManagerInfo>();
 6             foreach (DataRow row in table.Rows)
 7             {
 8                //對象初始化器
 9                 list.Add(new ManagerInfo()
10                 {
11                     Mid = Convert.ToInt32(row["mid"]),
12                     MName = row["mname"].ToString(),
13                     MPwd = row["mpwd"].ToString(),
14                     MType = Convert.ToInt32(row["mtype"])
15                 });
16             }
17             return list;
18     
19 }    
查詢數據

ManagerInfoBll中查詢數據庫的代碼:

1 /// <summary>
2         /// 數據查詢
3         /// </summary>
4         /// <returns></returns>
5         public List<ManagerInfo> GetList()
6         {
7             return miDal.GetList();
8         }
查詢數據BLL

在前端調用的時候 只需要創建ManagerInfoBll對象,調用其查詢數據方法即可。

//創建ManagerInfoBll對象,以后的調用都是通過這個對象進行的

ManagerInfoBll manager = new ManagerInfoBll();

//取得了查詢的數據

List<ManagerInfo> list = manager.GetList();

//咱們可以對這個數據集進行使用了。

2.添加操作:

UI層向BLL發送請求,即向數據庫添加數據,那么需要向BLL傳遞需要添加數據的數據模型

UI層代碼:

//創建 一個ManagerInfo對象

ManagerInfo mi = new ManagerInfo();

mi.MName = txtName.Text.ToString();
mi.MPwd = txtPwd.Text.ToString();
mi.MType = rb1.Checked ? 1 : 0;

//將mi作為數據模型傳給BLL

manager.Add(mi)

BLL層代碼:

1 public bool Add(ManagerInfo  mi)
2         {
3             return miDal.Insert(mi);
4         }
添加數據BLL

DAL層:首先會通過ManagerInfoDal層的代碼,來調用SqlHelper中對數據庫進行添加的代碼

ManagerInfoDal類:

 1 /// <summary>
 2         /// 插入數據
 3         /// </summary>
 4         /// <param name="mi">傳入的數據模型</param>
 5         /// <returns></returns>
 6         public bool Insert(ManagerInfo mi)
 7         {
 8             string strSql = "insert into managerinfo (mname,mpwd,mtype) values(@mname,@mpwd,@mtype)";
 9             SQLiteParameter[] param = new SQLiteParameter[] 
10             { 
11                 new SQLiteParameter("@mname", mi.MName),
12                 new SQLiteParameter("@mpwd",MD5Helper.Md5(mi.MPwd)),
13                 new SQLiteParameter("@mtype",mi.MType) 
14             };
15             return SQLiteHelper.ExecuteNonQuery(strSql, param) > 0;
16         }
添加數據ManagerInfoDal

在這里使用了SqlParameter 這個參數類,可以避免SQL注入

SQLiteHelper類:

 

 1 #region 向數據庫插入數據,刪除數據 修改數據  +ExecuteNonQuery(string sql)
 2         /// <summary>
 3         /// 向數據庫插入數據,刪除數據 修改數據
 4         /// </summary>
 5         /// <param name="sql"></param>
 6         /// <returns></returns>
 7         public static int ExecuteNonQuery(string sql, params SQLiteParameter[] param)
 8         {
 9             using (SQLiteConnection conn = new SQLiteConnection(strConn))
10             {
11                 SQLiteCommand cmd = new SQLiteCommand(sql, conn);
12                 conn.Open();
13                 cmd.Parameters.AddRange(param);
14                 return cmd.ExecuteNonQuery();
15             }
16         } 
17         #endregion
添加數據 SQLiteHelper

 

3.刪除操作:

一般刪除操作只需要根據主鍵進行刪除,那么UI層向BLL層傳遞數據時,只需要傳遞ID即可。

UI層:

manager.Remove(Mid)

BLL層:

1 public bool Remove(int id)
2         {
3             return miDal.DeleteById(id);
4         }
刪除數據 BLL

DAL層:

 1 /// <summary>
 2         /// 根據id 刪除數據
 3         /// </summary>
 4         /// <param name="id"></param>
 5         /// <returns></returns>
 6         public bool DeleteById(int id)
 7         {
 8             string strSql = "delete from managerinfo where mid=@id";
 9             SQLiteParameter[] param = new SQLiteParameter[] 
10             {
11                 new SQLiteParameter("@id",id)
12             };
13             return SQLiteHelper.ExecuteNonQuery(strSql, param) > 0;
14         }
根據id 刪除數據 DAL

SQLiteHelper類中ExecuteNonQuery()方法 可以共用刪除,添加,更新操作。

4.更新操作:

BLL層:

1 public bool Remove(int id)
2         {
3             return miDal.DeleteById(id);
4         }
更新操作 BLL

DAL層:

 1 /// <summary>
 2         /// 修改數據
 3         /// </summary>
 4         /// <param name="mi"></param>
 5         /// <returns></returns>
 6         public bool Update(ManagerInfo mi)
 7         {
 8             List<SQLiteParameter> list = new List<SQLiteParameter>();
 9             string strSql = "update managerinfo set mname=@mname,";
10             list.Add(new SQLiteParameter("@mname", mi.MName));
11             if (!mi.MPwd.Equals("******"))
12             {
13                 strSql += "mpwd=@mpwd,";
14                 list.Add(new SQLiteParameter("@mpwd", mi.MPwd));
15 
16             }
17             strSql += "mtype=@mtype where mid=@mid";
18             list.Add(new SQLiteParameter("@mtype", mi.MType));
19             list.Add(new SQLiteParameter("@mid", mi.Mid));
20             return SQLiteHelper.ExecuteNonQuery(strSql, list.ToArray()) > 0;
21         }
修改數據 DAL

 

 在這里,額外說一下MD5加密:

 1 public static string MD5(string str){
 2     //創建MD5對象
 3     MD5 md5=MD5.Create();
 4     //將數據轉換成字節數組
 5     byte[] bytes=Encoding.utf8.GetByte(str);  
 6     // 對字節數組進行加密
 7     byte[] bytes2= md5.ComputeHash(bytes);
 8     //將字節數組轉換成十六進制的字符串
 9     //1.創建stringBuilder對象
10      StringBuilder st = new StringBuilder();
11      for (int i = 0; i < bytes2.Length; i++)
12             {
13                 //將字節數組轉換成16位
14                 st.AppendFormat(bytes2[i].ToString("x2"));
15             }
16      return st.ToString();
17 }
MD5

MD5加密 是不可逆的 ,所以有時在保存密碼的時候需要MD5加密。

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM