ADO.NET快速上手实践总结

本文希望能给大家一些启发。前言:这两天重温经典,对ADO.NET的东西稍微深入的了解了一下,顺便写点代码练练手,全当是复习笔记吧。

创新互联主要从事成都网站设计、做网站、网页设计、企业做网站、公司建网站等业务。立足成都服务海西,十多年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18982081108

一、简单说说ADO.NET的5大常用对象

既然说ADO.NET,当然不能免俗地要提到5大常用对象。本文不会对ADO.NET的5大对象和它们的关系进行过多阐释,不过我们应该对下面这张图的结构有个了解:

关于上图图示中的5大对象,经常做以数据为驱动的mis系统的童鞋应该不会陌生。本文一笔带过。下面我们一步一步实现以ADO.NET为核心的数据访问程序。

二、数据访问持久化层

1、IDbOperation接口

  
 
 
 
  1. using System.Collections.Generic;  
  2. using System.Data;  
  3. using System.Data.Common;  
  4. namespace AdoNetDataAccess.Core.Contract  
  5. {  
  6.     public interface IDbOperation  
  7.     {  
  8.         DbCommand CreateDbCommd(DbConnection sqlConn, DbTransaction transaction, string sqlStr, CommandType cmdType, List listParams);  
  9.         DbParameter CreateDbPrameter(string paramName, object paramValue);  
  10.         DbDataReader ExecuteReader(string sqlStr, CommandType cmdType, List listParams);  
  11.         DataTable FillDataTable(string sqlStr, CommandType cmdType, List listParams);  
  12.         DataSet FillDataSet(string sqlStr, CommandType cmdType, List listParams);  
  13.         object ExecuteScalar(string sqlStr, CommandType cmdType, List listParams);  
  14.        int ExecuteNonQuery(string sqlStr, CommandType cmdType, List listParams);  
  15.         ///   
  16.         /// 批量插入  
  17.         ///   
  18.         /// 表名称  
  19.         /// 组装好的要批量导入的datatable  
  20.         ///   
  21.         bool ExecuteBatchInsert(string tableName, int batchSize, int copyTimeout, DataTable dt);  
  22.         void OpenConnection();  
  23.         void CloseConnection();  
  24.     }  

上面的接口包括增删改查,批量插入以及数据库连接对象的连接和关闭等常用操作,您可以根据命名和参数轻松理解函数的含义。根据楼猪的开发经验,对于平时的数据库操作,上述方法差不多够用了。当然您也可以按照自己需要,重写组织添加其他函数。

2、针对一种数据源的数据操作实现

底层的数据操作接口定义好后,就要针对一种数据源,具体实现上述的数据操作。这里楼猪选择了Sql Server。我们也可以实现其他数据源的数据访问操作,按照配置,利用抽象工厂动态反射选择是哪一种数据源的实现。这里按下不表,有心的童鞋自己可以动手一试。下面是具体的实现:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Common;  
  5. using System.Data.SqlClient;  
  6. using System.Transactions;  
  7. namespace AdoNetDataAccess.Core.Implement  
  8. {  
  9.     using AdoNetDataAccess.Core.Contract;  
  10.  
  11.     public class SqlServer : IDbOperation, IDisposable  
  12.     {  
  13.         private int cmdTimeOut = 60;  
  14.         private DbConnection sqlConn = null;  
  15.         private DbCommand cmd = null;  
  16.  
  17.         private SqlServer()  
  18.         {  
  19.         }  
  20.         public SqlServer(string sqlConStr)  
  21.         {  
  22.             sqlConn = new SqlConnection(sqlConStr);  
  23.             cmdTimeOut = sqlConn.ConnectionTimeout;  
  24.         }  
  25.         public SqlServer(string sqlConStr, int timeOut)  
  26.         {  
  27.             sqlConn = new SqlConnection(sqlConStr);  
  28.             if (timeOut < 0)  
  29.             {  
  30.                 timeOut = sqlConn.ConnectionTimeout;  
  31.             }  
  32.             cmdTimeOut = timeOut;  
  33.         }  
  34.         #region contract method  
  35.         public DbCommand CreateDbCommd(DbConnection sqlConn, DbTransaction transaction, string sqlStr, CommandType cmdType, List listParams)  
  36.         {  
  37.             DbCommand cmd = new SqlCommand();  
  38.             cmd.Connection = sqlConn;  
  39.             cmd.CommandText = sqlStr;  
  40.             cmd.CommandType = cmdType;  
  41.             if (transaction != null)  
  42.             {  
  43.                 cmd.Transaction = transaction;  
  44.             }  
  45.             if (listParams != null && listParams.Count > 0)  
  46.             {  
  47.                 cmd.Parameters.AddRange(listParams.ToArray());  
  48.             }  
  49.             cmd.CommandTimeout = cmdTimeOut;  
  50.             OpenConnection();  
  51.             return cmd;  
  52.         }  
  53.  
  54.         public DbParameter CreateDbPrameter(string paramName, object paramValue)  
  55.         {  
  56.             SqlParameter sp = new SqlParameter(paramName, paramValue);  
  57.             return sp;  
  58.         }  
  59.  
  60.         public DbDataReader ExecuteReader(string sqlStr, CommandType cmdType, List listParams)  
  61.         {  
  62.             DbDataReader rdr = null;  
  63.             try 
  64.             {  
  65.                 OpenConnection();  
  66.                 cmd = CreateDbCommd(sqlConn, null, sqlStr, cmdType, listParams);  
  67.                 rdr = cmd.ExecuteReader();  
  68.             }  
  69.             catch (Exception ex)  
  70.             {  
  71.                 throw ex;  
  72.             }  
  73.             return rdr;  
  74.         }  
  75.  
  76.         public DataTable FillDataTable(string sqlStr, CommandType cmdType, List listParams)  
  77.         {  
  78.             OpenConnection();  
  79.             DbTransaction trans = sqlConn.BeginTransaction();  
  80.             DbCommand cmd = CreateDbCommd(sqlConn, trans, sqlStr, cmdType, listParams);  
  81.             SqlDataAdapter sqlDataAdpter = new SqlDataAdapter(cmd as SqlCommand);  
  82.             DataTable dt = new DataTable();  
  83.             try 
  84.             {  
  85.                 sqlDataAdpter.Fill(dt);  
  86.                 trans.Commit();  
  87.             }  
  88.             catch (Exception e)  
  89.             {  
  90.                 trans.Rollback();  
  91.                 throw new Exception("执行数据库操作失败, sql: " + sqlStr, e);  
  92.             }  
  93.             finally 
  94.             {  
  95.                 sqlDataAdpter.Dispose();  
  96.                 cmd.Dispose();  
  97.                 trans.Dispose();  
  98.                 CloseConnection();  
  99.             }  
  100.             return dt;  
  101.         }  
  102.  
  103.         public DataSet FillDataSet(string sqlStr, CommandType cmdType, List listParams)  
  104.         {  
  105.             OpenConnection();  
  106.             DbTransaction trans = sqlConn.BeginTransaction();  
  107.             DbCommand cmd = CreateDbCommd(sqlConn, trans, sqlStr, cmdType, listParams);  
  108.             SqlDataAdapter sqlDataAdpter = new SqlDataAdapter(cmd as SqlCommand);  
  109.             DataSet ds = new DataSet();  
  110.             try 
  111.             {  
  112.                 sqlDataAdpter.Fill(ds);  
  113.                 trans.Commit();  
  114.             }  
  115.             catch (Exception e)  
  116.             {  
  117.                 trans.Rollback();  
  118.                 throw new Exception("执行数据库操作失败, sql: " + sqlStr, e);  
  119.             }  
  120.             finally 
  121.             {  
  122.                 sqlDataAdpter.Dispose();  
  123.                 cmd.Dispose();  
  124.                 trans.Dispose();  
  125.                 CloseConnection();  
  126.             }  
  127.             return ds;  
  128.         }  
  129.  
  130.         public object ExecuteScalar(string sqlStr, CommandType cmdType, List listParams)  
  131.         {  
  132.             object result = null;  
  133.             OpenConnection();  
  134.             DbTransaction trans = sqlConn.BeginTransaction();  
  135.             try 
  136.             {  
  137.                 cmd = CreateDbCommd(sqlConn, trans, sqlStr, cmdType, listParams);  
  138.                 result = cmd.ExecuteScalar();  
  139.                 trans.Commit();  
  140.             }  
  141.             catch (Exception e)  
  142.             {  
  143.                 trans.Rollback();  
  144.                 throw new Exception("执行数据库操作失败, sql: " + sqlStr, e);  
  145.             }  
  146.             finally 
  147.             {  
  148.                 trans.Dispose();  
  149.                 CloseConnection();  
  150.             }  
  151.             return result;  
  152.         }  
  153.  
  154.         public int ExecuteNonQuery(string sqlStr, CommandType cmdType, List listParams)  
  155.         {  
  156.             int result = -1;  
  157.             OpenConnection();  
  158.             DbTransaction trans = sqlConn.BeginTransaction();  
  159.             try 
  160.             {  
  161.                 cmd = CreateDbCommd(sqlConn, trans, sqlStr, cmdType, listParams);  
  162.                 result = cmd.ExecuteNonQuery();  
  163.                 trans.Commit();  
  164.             }  
  165.             catch (Exception e)  
  166.             {  
  167.                 trans.Rollback();  
  168.                 throw new Exception("执行数据库操作失败, sql: " + sqlStr, e);  
  169.             }  
  170.             finally 
  171.             {  
  172.                 trans.Dispose();  
  173.                 CloseConnection();  
  174.             }  
  175.             return result;  
  176.         }  
  177.  
  178.         ///   
  179.         /// 批量插入  
  180.         ///   
  181.         ///   
  182.         ///   
  183.         ///   
  184.         ///   
  185.         ///   
  186.         public bool ExecuteBatchInsert(string tableName, int batchSize, int copyTimeout, DataTable dt)  
  187.         {  
  188.             bool flag = false;  
  189.             try 
  190.             {  
  191.                 using (TransactionScope scope = new TransactionScope())  
  192.                 {  
  193.                     OpenConnection();  
  194.                     using (SqlBulkCopy sbc = new SqlBulkCopy(sqlConn as SqlConnection))  
  195.                     {  
  196.                         //服务器上目标表的名称  
  197.                         sbc.DestinationTableName = tableName;  
  198.                         sbc.BatchSize = batchSize;  
  199.                         sbc.BulkCopyTimeout = copyTimeout;  
  200.                         for (int i = 0; i < dt.Columns.Count; i++)  
  201.                         {  
  202.                             //列映射定义数据源中的列和目标表中的列之间的关系  
  203.                             sbc.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);  
  204.                         }  
  205.                         sbc.WriteToServer(dt);  
  206.                         flag = true;  
  207.                         scope.Complete();//有效的事务  
  208.                     }  
  209.                 }  
  210.             }  
  211.             catch (Exception ex)  
  212.             {  
  213.                 throw ex;  
  214.             }  
  215.             return flag;  
  216.         }  
  217.         public void OpenConnection()  
  218.         {  
  219.             if (sqlConn.State == ConnectionState.Broken || sqlConn.State == ConnectionState.Closed)  
  220.                 sqlConn.Open();  
  221.         }  
  222.         public void CloseConnection()  
  223.         {  
  224.             sqlConn.Close();  
  225.         }  
  226.         #endregion  
  227.         #region dispose method  
  228.  
  229.         ///   
  230.         /// dispose接口方法  
  231.         ///   
  232.         public void Dispose()  
  233.         {  
  234.         }  
  235.         #endregion  
  236.     }  
 

   

到这里,我们实现了SqlServer类里的方法,对Ms SqlServer数据库我们就已经可以进行简单的基础的CRUD操作了。

三、简单直观的对象实体转换

在第二步中,我们已经实现了简单的数据CRUD操作。根据楼猪使用ORM的经验和习惯,我们也应该对一些查询结果进行转换,因为以类的组织方式比直接呈现ADO.NET对象更容易让人接受,效率高低反在其次。下面利用常见的反射原理,简单实现一个对象实体转换器ModelConverter类:

   
 
 
 
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Data;  
  5. using System.Data.Common;  
  6. using System.Reflection;  
  7. using System.Threading;  
  8. namespace AdoNetDataAccess.Core.Obj2Model  
  9. {  
  10.     using AdoNetDataAccess.Core.Contract;  
  11.  
  12.     public sealed class ModelConverter  
  13.     {  
  14.         private static readonly object objSync = new object();  
  15.  
  16.         #region query for list  
  17.  
  18.         ///   
  19.         /// 查询数据表项并转换为对应实体  
  20.         ///   
  21.         ///   
  22.         ///   
  23.         ///   
  24.         ///   
  25.         public static IList QueryForList(string sqlStr, CommandType cmdType, List listParams, Type objType, IDbOperation dbOperation)  
  26.             where T : class, new()  
  27.         {  
  28.             IDataReader rdr = dbOperation.ExecuteReader(sqlStr, cmdType, listParams);  
  29.             IList listModels = new List();  
  30.             try 
  31.             {  
  32.                 Monitor.Enter(objSync);  
  33.                 Hashtable ht = CreateHashColumnName(rdr);  
  34.                 while (rdr.Read())  
  35.                 {  
  36.                     Object obj = Activator.CreateInstance(objType);  
  37.                     PropertyInfo[] properties = objType.GetProperties();  
  38.                     foreach (PropertyInfo propInfo in properties)  
  39.                     {  
  40.                         string columnName = propInfo.Name.ToUpper();  
  41.                         if (ht.ContainsKey(columnName) == false)  
  42.                         {  
  43.                             continue;  
  44.                         }  
  45.                         int index = rdr.GetOrdinal(propInfo.Name);  
  46.                         object columnValue = rdr.GetValue(index);  
  47.                         if (columnValue != System.DBNull.Value)  
  48.                         {  
  49.                             SetValue(propInfo, obj, columnValue);  
  50.                         }  
  51.                     }  
  52.                     T model = default(T);  
  53.                     model = obj as T;  
  54.                     listModels.Add(model);  
  55.                 }  
  56.             }  
  57.             finally 
  58.             {  
  59.                 rdr.Close();  
  60.                 rdr.Dispose();  
  61.                 Monitor.Exit(objSync);  
  62.             }  
  63.             return listModels;  
  64.         }  
  65.  
  66.         #endregion  
  67.  
  68.         #region query for dictionary  
  69.  
  70.         ///   
  71.         /// 查询数据表项并转换为对应实体  
  72.         ///   
  73.         ///   
  74.         ///   
  75.         /// 字典对应key列名  
  76.         ///   
  77.         ///   
  78.         ///   
  79.         public static IDictionary QueryForDictionary
  80. (string key, string sqlStr, CommandType cmdType, List listParams, Type objType, IDbOperation dbOperation)  
  81.             where T : class, new()  
  82.         {  
  83.             IDataReader rdr = dbOperation.ExecuteReader(sqlStr, cmdType, listParams);  
  84.             IDictionary dictModels = new Dictionary();  
  85.             try 
  86.             {  
  87.                 Monitor.Enter(objSync);  
  88.                 Hashtable ht = CreateHashColumnName(rdr);  
  89.                 while (rdr.Read())  
  90.                 {  
  91.                     Object obj = Activator.CreateInstance(objType);  
  92.                     PropertyInfo[] properties = objType.GetProperties();  
  93.                     object dictKey = null;  
  94.                     foreach (PropertyInfo propInfo in properties)  
  95.                     {  
  96.                         string columnName = propInfo.Name.ToUpper();  
  97.                         if (ht.ContainsKey(columnName) == false)  
  98.                         {  
  99.                             continue;  
  100.                         }  
  101.                         int index = rdr.GetOrdinal(propInfo.Name);  
  102.                         object columnValue = rdr.GetValue(index);  
  103.                         if (columnValue != System.DBNull.Value)  
  104.                         {  
  105.                             SetValue(propInfo, obj, columnValue);  
  106.                             if (string.Compare(columnName, key.ToUpper()) == 0)  
  107.                             {  
  108.                                 dictKey = columnValue;  
  109.                             }  
  110.                         }  
  111.                     }  
  112.                     T model = default(T);  
  113.                     model = obj as T;  
  114.                     K objKey = (K)dictKey;  
  115.                     dictModels.Add(objKey, model);  
  116.                 }  
  117.             }  
  118.             finally 
  119.             {  
  120.                 rdr.Close();  
  121.                 rdr.Dispose();  
  122.                 Monitor.Exit(objSync);  
  123.             }  
  124.             return dictModels;  
  125.         }  
  126.  
  127.         #endregion  
  128.  
  129.         #region internal util  
  130.  
  131.         private static Hashtable CreateHashColumnName(IDataReader rdr)  
  132.         {  
  133.             int len = rdr.FieldCount;  
  134.             Hashtable ht = new Hashtable(len);  
  135.             for (int i = 0; i < len; i++)  
  136.             {  
  137.                 string columnName = rdr.GetName(i).ToUpper(); //不区分大小写  
  138.                 string columnRealName = rdr.GetName(i);  
  139.                 if (ht.ContainsKey(columnName) == false)  
  140.                 {  
  141.                     ht.Add(columnName, columnRealName);  
  142.                 }  
  143.             }  
  144.             return ht;  
  145.         }  
  146.  
  147.         private static void SetValue(PropertyInfo propInfo, Object obj, object objValue)  
  148.         {  
  149.             try 
  150.             {  
  151.                 propInfo.SetValue(obj, objValue, 

    文章标题:ADO.NET快速上手实践总结
    分享地址:http://www.csdahua.cn/qtweb/news18/121818.html

    网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

    广告

    声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网