zoukankan      html  css  js  c++  java
  • ADO.Net 精简的三层架构

    DAL(Data Access Layer)

    三层架构是企业开发中常用的设计模式,把数据库访问、业务逻辑、界面分离。

    初学者直接学习三层架构比较难,因此先学习精简的三层架构,只用DAL层,把数据库访问封装到DAL中,UI调用DAL,原则“UI中不出现SQL”。

    DAL常用封装:ToModel、ListAll、GetById、DeleteById、Update、Insert

    下面是一个使用DAL的实例:

    数据库表

    T_Customer定义

    代码清单:

    配置文件:App.config

    1. <?xml version="1.0" encoding="utf-8" ?>  
    2. <configuration>  
    3.   <connectionStrings>  
    4.     <add name="myconnstr" connectionString="Data Source=.; Initial Catalog = ADOTest; User ID = sa; Password = 123456"/>  
    5.   </connectionStrings>  
    6. </configuration>  


     

    /Model:模型类

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5.   
    6. namespace ADOTest5.Model  
    7. {  
    8.     public class Customer  
    9.     {  
    10.         public long Id {get;set;}  
    11.         public string Name { getset; }  
    12.         public DateTime? Birthday { getset; }  
    13.         public string Address { getset; }  
    14.         public string TelNum { getset; }  
    15.         public int CustLevel { getset; }  
    16.     }  
    17. }  


     

    /DAL/CustomerDAL.cs

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using ADOTest5.Model;  
    6. using System.Data;  
    7. using System.Data.SqlClient;  
    8.   
    9. namespace ADOTest5.DAL  
    10. {  
    11.     public  class CustomerDAL  
    12.     {  
    13.         //根据Id获取GetById、Update、DeleteById、GetAll、GetPagedData(分页数据)  
    14.         //Insert(插入新数据)  
    15.   
    16.         //把公共的代码封装到一个方法中,这样可以避免重复性的代码,提高代码复用性  
    17.         private Customer ToCustomer(DataRow row)  
    18.         {  
    19.             Customer cust = new Customer();  
    20.             cust.Id = (int)row["Id"];  
    21.             cust.Name = (string)row["Name"];  
    22.             cust.Birthday = (DateTime?)SqlHelper.FromDbValue(row["Birthday"]);  
    23.             cust.Address = (string)row["Address"];  
    24.             cust.CustLevel = (int)row["CustLevel"];  
    25.             cust.TelNum = (string)row["TelNum"];  
    26.             return cust;  
    27.         }  
    28.         /// <summary>  
    29.         /// 根据Id查询结果  
    30.         /// </summary>  
    31.         /// <param name="id"></param>  
    32.         /// <returns></returns>  
    33.         public Customer GetById(long id)  
    34.         {  
    35.             DataTable dt = SqlHelper.ExecuteDataTable("select * from T_Customer where Id = @Id"  
    36.                 ,new SqlParameter("@Id",id));  
    37.             if (dt.Rows.Count <= 0)  
    38.             {  
    39.                 return null;  
    40.             }  
    41.             else if (dt.Rows.Count > 1)  
    42.             {  
    43.                 throw new Exception("严重错误,查出多条数据!");  
    44.             }  
    45.             else  
    46.             {  
    47.                 DataRow row = dt.Rows[0];  
    48.                 return ToCustomer(row);  
    49.             }  
    50.         }  
    51.   
    52.         /// <summary>  
    53.         /// 根据Id删除数据  
    54.         /// </summary>  
    55.         /// <param name="id"></param>  
    56.         public void DeleteById(long id)  
    57.         {  
    58.             SqlHelper.ExecuteNonQuery("delete from T_Customer where Id = @Id",  
    59.                 new SqlParameter("@Id", id));  
    60.   
    61.         }  
    62.   
    63.         /// <summary>  
    64.         /// 往数据库中插入数据  
    65.         /// </summary>  
    66.         /// <param name="customer"></param>  
    67.         public void Insert(Customer customer)  
    68.         {  
    69.             SqlHelper.ExecuteNonQuery(@"Insert into T_Customer(Name,  
    70.                 Birthday, Address, TelNum, CustLevel)  
    71.                 values(@Name, @Birthday, @Address, @TelNum, @CustLevel)",  
    72.                 new SqlParameter("@Name",customer.Name),  
    73.                 new SqlParameter("@Birthday",SqlHelper.ToDbValue(customer.Birthday)),  
    74.                 new SqlParameter("@Address", customer.Address),  
    75.                 new SqlParameter("@TelNum", customer.TelNum),  
    76.                 new SqlParameter("@CustLevel",customer.CustLevel));  
    77.         }  
    78.   
    79.         /// <summary>  
    80.         /// 更新数据  
    81.         /// </summary>  
    82.         /// <param name="customer"></param>  
    83.         public void Update(Customer customer)  
    84.         {  
    85.             SqlHelper.ExecuteNonQuery(@"Update T_Customer set   
    86.                     Name = @Name, Birthday = @Birthday, Address = @Address,  
    87.                     TelNum = @TelNum, CustLevel = @CustLevel   
    88.                     where Id = @Id",  
    89.                     new SqlParameter("@Name", customer.Name),  
    90.                     new SqlParameter("@Birthday", SqlHelper.ToDbValue(customer.Birthday)),  
    91.                     new SqlParameter("@Address", customer.Address),  
    92.                     new SqlParameter("@TelNum", customer.TelNum),  
    93.                     new SqlParameter("@CustLevel", customer.CustLevel));  
    94.         }  
    95.   
    96.   
    97.         /// <summary>  
    98.         /// 查询所有数据  
    99.         /// </summary>  
    100.         /// <returns></returns>  
    101.         public Customer[] GetAll()  
    102.         {  
    103.             DataTable table = SqlHelper.ExecuteDataTable("select * from T_Customer");  
    104.             Customer[] customers = new Customer[table.Rows.Count];  
    105.             for (int i = 0; i < table.Rows.Count; i++)  
    106.             {  
    107.                 DataRow row = table.Rows[i];  
    108.                 customers[i] = ToCustomer(row);  
    109.             }  
    110.             return customers;  
    111.         }  
    112.   
    113.     }  
    114. }  


     

    /DAL/SqlHelper.cs

      1. using System;  
      2. using System.Collections.Generic;  
      3. using System.Linq;  
      4. using System.Text;  
      5. using System.Configuration;  
      6. using System.Data.SqlClient;  
      7. using System.Data;  
      8.   
      9. namespace ADOTest5.DAL  
      10. {  
      11.     static class SqlHelper  
      12.     {  
      13.         public static readonly string connstr = ConfigurationManager.ConnectionStrings["myconnstr"].ConnectionString;  
      14.   
      15.         public static int ExecuteNonQuery(string sql,  
      16.             params SqlParameter[] parameters)  
      17.         {  
      18.             using (SqlConnection conn = new SqlConnection(connstr))  
      19.             {  
      20.                 conn.Open();  
      21.                 using (SqlCommand cmd = conn.CreateCommand())  
      22.                 {  
      23.                     cmd.CommandText = sql;  
      24.                     cmd.Parameters.AddRange(parameters);  
      25.                     return cmd.ExecuteNonQuery();  
      26.                 }  
      27.             }  
      28.         }  
      29.   
      30.         public static object ExecuteScalar(string sql,  
      31.             params SqlParameter[] parameters)  
      32.         {  
      33.             using (SqlConnection conn = new SqlConnection(connstr))  
      34.             {  
      35.                 conn.Open();  
      36.                 using (SqlCommand cmd = conn.CreateCommand())  
      37.                 {  
      38.                     cmd.CommandText = sql;  
      39.                     cmd.Parameters.AddRange(parameters);  
      40.                     return cmd.ExecuteScalar();  
      41.                 }  
      42.             }  
      43.         }  
      44.   
      45.   
      46.         public static DataTable ExecuteDataTable(string sql,  
      47.             params SqlParameter[] parameters)  
      48.         {  
      49.             using (SqlConnection conn = new SqlConnection(connstr))  
      50.             {  
      51.                 conn.Open();  
      52.                 using (SqlCommand cmd = conn.CreateCommand())  
      53.                 {  
      54.                     cmd.CommandText = sql;  
      55.                     cmd.Parameters.AddRange(parameters);  
      56.                     DataSet ds = new DataSet();  
      57.                     SqlDataAdapter adapter = new SqlDataAdapter(cmd);  
      58.                     adapter.Fill(ds);  
      59.                     return ds.Tables[0];  
      60.                 }  
      61.             }  
      62.         }  
      63.   
      64.         public static object FromDbValue(object value)  
      65.         {  
      66.             if (value == DBNull.Value)  
      67.             {  
      68.                 return null;  
      69.             }  
      70.             else  
      71.             {  
      72.                 return value;  
      73.             }  
      74.         }  
      75.   
      76.         public static object ToDbValue(object value)  
      77.         {  
      78.             if (value == null)  
      79.             {  
      80.                 return DBNull.Value;  
      81.             }  
      82.             else  
      83.             {  
      84.                 return value;  
      85.             }  
      86.         }  
      87.     }  

  • 相关阅读:
    【Go学习笔记】 string转Map 和 Map嵌套取值 和 interface转string
    【Go 学习】Go 正则类似Python findall()方法
    【Go学习】Go mod 包管理
    构建之法阅读笔记(四)
    nltk安装配置以及语料库的安装配置
    机器学习KNN算法实现新闻文本分类思路总结
    KNN算法源代码
    构建之法阅读笔记(三)
    jupyter反爬虫
    python多条件模糊查询
  • 原文地址:https://www.cnblogs.com/shixunle/p/3330290.html
Copyright © 2011-2022 走看看