日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
ADO.NET快速上手實(shí)踐總結(jié)

本文希望能給大家一些啟發(fā)。前言:這兩天重溫經(jīng)典,對ADO.NET的東西稍微深入的了解了一下,順便寫點(diǎn)代碼練練手,全當(dāng)是復(fù)習(xí)筆記吧。

創(chuàng)新互聯(lián)主要從事成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)海西,十多年網(wǎng)站建設(shè)經(jīng)驗(yàn),價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):18982081108

一、簡單說說ADO.NET的5大常用對象

既然說ADO.NET,當(dāng)然不能免俗地要提到5大常用對象。本文不會對ADO.NET的5大對象和它們的關(guān)系進(jìn)行過多闡釋,不過我們應(yīng)該對下面這張圖的結(jié)構(gòu)有個了解:

關(guān)于上圖圖示中的5大對象,經(jīng)常做以數(shù)據(jù)為驅(qū)動的mis系統(tǒng)的童鞋應(yīng)該不會陌生。本文一筆帶過。下面我們一步一步實(shí)現(xiàn)以ADO.NET為核心的數(shù)據(jù)訪問程序。

二、數(shù)據(jù)訪問持久化層

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.         /// 組裝好的要批量導(dǎo)入的datatable  
  20.         ///   
  21.         bool ExecuteBatchInsert(string tableName, int batchSize, int copyTimeout, DataTable dt);  
  22.         void OpenConnection();  
  23.         void CloseConnection();  
  24.     }  

上面的接口包括增刪改查,批量插入以及數(shù)據(jù)庫連接對象的連接和關(guān)閉等常用操作,您可以根據(jù)命名和參數(shù)輕松理解函數(shù)的含義。根據(jù)樓豬的開發(fā)經(jīng)驗(yàn),對于平時的數(shù)據(jù)庫操作,上述方法差不多夠用了。當(dāng)然您也可以按照自己需要,重寫組織添加其他函數(shù)。

2、針對一種數(shù)據(jù)源的數(shù)據(jù)操作實(shí)現(xiàn)

底層的數(shù)據(jù)操作接口定義好后,就要針對一種數(shù)據(jù)源,具體實(shí)現(xiàn)上述的數(shù)據(jù)操作。這里樓豬選擇了Sql Server。我們也可以實(shí)現(xiàn)其他數(shù)據(jù)源的數(shù)據(jù)訪問操作,按照配置,利用抽象工廠動態(tài)反射選擇是哪一種數(shù)據(jù)源的實(shí)現(xiàn)。這里按下不表,有心的童鞋自己可以動手一試。下面是具體的實(shí)現(xiàn):

  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("執(zhí)行數(shù)據(jù)庫操作失敗, 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("執(zhí)行數(shù)據(jù)庫操作失敗, 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("執(zhí)行數(shù)據(jù)庫操作失敗, 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("執(zhí)行數(shù)據(jù)庫操作失敗, 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.                         //服務(wù)器上目標(biāo)表的名稱  
  197.                         sbc.DestinationTableName = tableName;  
  198.                         sbc.BatchSize = batchSize;  
  199.                         sbc.BulkCopyTimeout = copyTimeout;  
  200.                         for (int i = 0; i < dt.Columns.Count; i++)  
  201.                         {  
  202.                             //列映射定義數(shù)據(jù)源中的列和目標(biāo)表中的列之間的關(guān)系  
  203.                             sbc.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);  
  204.                         }  
  205.                         sbc.WriteToServer(dt);  
  206.                         flag = true;  
  207.                         scope.Complete();//有效的事務(wù)  
  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.     }  
 

   

到這里,我們實(shí)現(xiàn)了SqlServer類里的方法,對Ms SqlServer數(shù)據(jù)庫我們就已經(jīng)可以進(jìn)行簡單的基礎(chǔ)的CRUD操作了。

三、簡單直觀的對象實(shí)體轉(zhuǎn)換

在第二步中,我們已經(jīng)實(shí)現(xiàn)了簡單的數(shù)據(jù)CRUD操作。根據(jù)樓豬使用ORM的經(jīng)驗(yàn)和習(xí)慣,我們也應(yīng)該對一些查詢結(jié)果進(jìn)行轉(zhuǎn)換,因?yàn)橐灶惖慕M織方式比直接呈現(xiàn)ADO.NET對象更容易讓人接受,效率高低反在其次。下面利用常見的反射原理,簡單實(shí)現(xiàn)一個對象實(shí)體轉(zhuǎn)換器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.         /// 查詢數(shù)據(jù)表項(xiàng)并轉(zhuǎn)換為對應(yīng)實(shí)體  
  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.         /// 查詢數(shù)據(jù)表項(xiàng)并轉(zhuǎn)換為對應(yīng)實(shí)體  
  72.         ///   
  73.         ///   
  74.         ///   
  75.         /// 字典對應(yīng)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(); //不區(qū)分大小寫  
  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, 
    本文標(biāo)題:ADO.NET快速上手實(shí)踐總結(jié)
    當(dāng)前網(wǎng)址:http://m.5511xx.com/article/dhcsped.html