C#操做SqlServer MySql Oracle通用幫助類Db_Helper_DG(默認支持數據庫讀寫分離、查詢結果實體映射ORM)

【前言】

  做爲一款成熟的面向對象高級編程語言,C#在ADO.Net的支持上已然是作的很成熟,咱們能夠方便地調用ADO.Net操做各種關係型數據庫,在使用了多年的Sql_Helper_DG後,因爲項目須要,因而乎,就準備寫一個Mysql_Helper在實現過程當中,發現ADO.Net封裝之完善,以及面向對象的封裝、繼承、多態,有了這些特性,何不把數據庫操做封裝成爲一個通用的類呢,此文由此鋪展而來...git

【實現功能】

  這篇文章將要介紹的主要內容以下:github

  一、ADO.NET之SqlServer

  二、ADO.NET之Oracle

  三、ADO.NET之MySql

  四、充分利用面向對象的特徵,實現通用的操做類

【環境準備】

  一、MySql鏈接器的DLL引用

  使用Nuget搜索 MySql.Data 引用便可:web

  

  二、Oracle鏈接器的DLL引用

   使用Nuget搜索 Oracle.ManagedDataAccess 進行引用:sql

  

【實現思路】

  在ADO.NET對SqlServer,Oracle,Mysql的操做熟練的基礎上,咱們逐漸發現全部的操做都是使用的同一套的東西,不一樣的是:數據庫

  SqlServer的操做使用的是SqlConnection、SqlCommand,SqlDataAdapter;編程

  MySql使用的是MySqlConnection、MySqlCommand、MySqlDataAdapter;數組

  Oracle使用的是OracleSqlConnection、OracleCommand、OracleDataAdapter;併發

  該鏈接類,操做類都分別繼承自基礎類:DbConnection、DbCommand、DbDataAdapter;框架

  其類間關係如圖所示:編程語言

  1.DbConnection家族

  

  2.DbCommand家族

  

  3.DBDataAdapter家族

  

  瞭解如上的幾個特色後,咱們裏面能聯繫到了「多態」這個概念,咱們可使用同一套相同的代碼,用「多態」的特性實例化出不一樣的實例,進而能夠進一步封裝咱們的操做,達到代碼精煉可重用的目的。

【實現過程】

  1.定義枚舉類 Opt_DataBaseType 用於參數選擇具體要實例的數據庫

1 public enum Opt_DataBaseType
2 {
3         SqlServer,
4         MySql,
5         Oracle
6 }

  2.自定義內部類SqlConnection_WR_Safe(多態提供DbConnection的對象、讀寫分離的支持)

  1.在該內部類中,咱們定義類屬性DbConnection用於承接根據不一樣的數據庫參數多態實例化後的對應Connection
  2.實現IDisposable接口,提供釋放DbConnection的方法
  3.在讀數據庫鏈接失敗時,及時切換到讀寫主數據庫,提高系統的可用性

 1     internal class SqlConnection_WR_Safe : IDisposable
 2     {
 3         /// <summary>
 4         /// SqlConnection
 5         /// </summary>
 6         public DbConnection DbConnection { get; set; }
 7 
 8         public SqlConnection_WR_Safe(Opt_DataBaseType dataBaseType, string ConnString_RW)
 9         {
10             this.DbConnection = GetDbConnection(dataBaseType, ConnString_RW);
11         }
12         /**
13          * if read db disabled,switchover to read write db immediately
14          * */
15         public SqlConnection_WR_Safe(Opt_DataBaseType dataBaseType, string ConnString_R, string ConnString_RW)
16         {
17             try
18             {
19                 this.DbConnection = GetDbConnection(dataBaseType, ConnString_R);
20             }
21             catch (Exception)
22             {
23                 this.DbConnection = GetDbConnection(dataBaseType, ConnString_RW);
24             }
25         }
26 
27         /// <summary>
28         /// GetDataBase ConnectionString by database type and connection string -- private use
29         /// </summary>
30         /// <param name="dataBaseType"></param>
31         /// <param name="ConnString"></param>
32         /// <returns></returns>
33         private DbConnection GetDbConnection(Opt_DataBaseType dataBaseType, string ConnString)
34         {
35             switch (dataBaseType)
36             {
37                 case Opt_DataBaseType.SqlServer:
38                     return new SqlConnection(ConnString);
39                 case Opt_DataBaseType.MySql:
40                     return new MySqlConnection(ConnString);
41                 case Opt_DataBaseType.Oracle:
42                     return new OracleConnection(ConnString);
43                 default:
44                     return new SqlConnection(ConnString);
45             }
46         }
47         /// <summary>
48         /// Must Close Connection after use
49         /// </summary>
50         public void Dispose()
51         {
52             if (this.DbConnection != null)
53             {
54                 this.DbConnection.Dispose();
55             }
56         }
57     }

  3.自定義內部類 DbCommandCommon 用於提供DbCommand對象

 1     internal class DbCommandCommon : IDisposable
 2     {
 3         /// <summary>
 4         /// common dbcommand
 5         /// </summary>
 6         public DbCommand DbCommand { get; set; }
 7         public DbCommandCommon(Opt_DataBaseType dataBaseType)
 8         {
 9             this.DbCommand = GetDbCommand(dataBaseType);
10         }
11 
12         /// <summary>
13         /// Get DbCommand select database type
14         /// </summary>
15         /// <param name="dataBaseType"></param>
16         /// <returns></returns>
17         private DbCommand GetDbCommand(Opt_DataBaseType dataBaseType)
18         {
19             switch (dataBaseType)
20             {
21                 case Opt_DataBaseType.SqlServer:
22                     return new SqlCommand();
23                 case Opt_DataBaseType.MySql:
24                     return new MySqlCommand();
25                 case Opt_DataBaseType.Oracle:
26                     return new OracleCommand();
27                 default:
28                     return new SqlCommand();
29             }
30         }
31         /// <summary>
32         /// must dispose after use
33         /// </summary>
34         public void Dispose()
35         {
36             if (this.DbCommand != null)
37             {
38                 this.DbCommand.Dispose();
39             }
40         }
41     }

  4.自定義內部類 DbDataAdapterCommon 用於提供DbDataAdapter

  該類繼承自DbDataAdapter,以實現DataAdapter的Fill方法,能夠將結果集填充到DataSet中去。

 1     /// <summary>
 2     /// DbDataAdapterCommon
 3     /// </summary>
 4     internal class DbDataAdapterCommon : DbDataAdapter, IDisposable
 5     {
 6         public DbDataAdapter DbDataAdapter { get; set; }
 7         public DbDataAdapterCommon(Opt_DataBaseType dataBaseType, DbCommand dbCommand)
 8         {
 9             //get dbAdapter
10             this.DbDataAdapter = GetDbAdapter(dataBaseType, dbCommand);
11             //provid select command
12             this.SelectCommand = dbCommand;
13         }
14         private DbDataAdapter GetDbAdapter(Opt_DataBaseType dataBaseType, DbCommand dbCommand)
15         {
16             switch (dataBaseType)
17             {
18                 case Opt_DataBaseType.SqlServer:
19                     return new SqlDataAdapter();
20                 case Opt_DataBaseType.MySql:
21                     return new MySqlDataAdapter();
22                 case Opt_DataBaseType.Oracle:
23                     return new OracleDataAdapter();
24                 default:
25                     return new SqlDataAdapter();
26             }
27         }
28         /// <summary>
29         /// must dispose after use
30         /// </summary>
31         public new void Dispose()
32         {
33             if (this.DbDataAdapter != null)
34             {
35                 this.DbDataAdapter.Dispose();
36             }
37         }
38     }

   5.在執行Sql查詢的時候,咱們便使用咱們自定義的內部類進行操做

  >1 這裏以ExecuteNonQuery爲例:

    

 1 public static int ExecuteNonQuery(string commandTextOrSpName, CommandType commandType = CommandType.Text)
 2 {
 3     using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_RW))
 4     {
 5         using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
 6         {
 7             PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType);
 8             return cmd.DbCommand.ExecuteNonQuery();
 9         }
10     }
11 }

  該代碼經過參數DataBaseType肯定要實例化的數據庫類型,ConnString_RW傳入寫數據庫的鏈接字符串進行實例化,DbCommand也是使用dataBaseType實例咱們須要實際操做的數據庫對象。
  >2 查詢ExecuteDataSet方法:

  

  該方法經過參數dataBaseType肯定要實例化的具體DbConnection,經過讀寫分離的鏈接字符串進行選擇讀庫和寫庫。

 1 public static DataSet ExecuteDataSet(string commandTextOrSpName, CommandType commandType = CommandType.Text)
 2 {
 3     using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW))
 4     {
 5         using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
 6         {
 7             PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType);
 8             using (DbDataAdapterCommon da = new DbDataAdapterCommon(dataBaseType, cmd.DbCommand))
 9             {
10                 DataSet ds = new DataSet();
11                 da.Fill(ds);
12                 return ds;
13             }
14         }
15     }
16 }

 所有代碼見此:

  一、數據庫選擇器枚舉類:Opt_DataBaseType->

 1 /*********************************************************
 2  * CopyRight: QIXIAO CODE BUILDER. 
 3  * Version:4.2.0
 4  * Author:qixiao(柒小)
 5  * Create:2017-09-26 17:54:28
 6  * Update:2017-09-26 17:54:28
 7  * E-mail: dong@qixiao.me | wd8622088@foxmail.com 
 8  * GitHub: https://github.com/dong666 
 9  * Personal web site: http://qixiao.me 
10  * Technical WebSit: http://www.cnblogs.com/qixiaoyizhan/ 
11  * Description:
12  * Thx , Best Regards ~
13  *********************************************************/
14 namespace QX_Frame.Bantina.Options
15 {
16     public enum Opt_DataBaseType
17     {
18         SqlServer,
19         MySql,
20         Oracle
21     }
22 }
View Code

  二、主類代碼Db_Helper_DG->

  1 /*********************************************************
  2  * CopyRight: QIXIAO CODE BUILDER. 
  3  * Version:4.2.0
  4  * Author:qixiao(柒小)
  5  * Create:2017-9-26 17:41:42
  6  * Update:2017-9-26 17:41:42
  7  * E-mail: dong@qixiao.me | wd8622088@foxmail.com 
  8  * GitHub: https://github.com/dong666 
  9  * Personal web site: http://qixiao.me 
 10  * Technical WebSit: http://www.cnblogs.com/qixiaoyizhan/ 
 11  * Description:
 12  * Thx , Best Regards ~
 13  *********************************************************/
 14 using MySql.Data.MySqlClient;
 15 using Oracle.ManagedDataAccess.Client;
 16 using QX_Frame.Bantina.Options;
 17 using System;
 18 using System.Collections.Generic;
 19 using System.ComponentModel;
 20 using System.Data;
 21 using System.Data.Common;
 22 using System.Data.SqlClient;
 23 using System.Linq;
 24 using System.Reflection;
 25 
 26 namespace QX_Frame.Bantina
 27 {
 28     public abstract class Db_Helper_DG
 29     {
 30         #region ConnString 連接字符串聲明
 31 
 32         /// <summary>
 33         /// 鏈接字符串 ConnString_Default 默認,且賦值時會直接覆蓋掉讀寫
 34         /// </summary>
 35         private static string _connString = Configs.QX_Frame_Helper_DG_Config.ConnectionString_DB_QX_Frame_Default;
 36         public static string ConnString_Default
 37         {
 38             get { return _connString; }
 39             set
 40             {
 41                 _connString = value;
 42                 ConnString_RW = _connString;
 43                 ConnString_R = _connString;
 44             }
 45         }
 46         /// <summary>
 47         /// 鏈接字符串 ConnString_RW 讀寫數據庫使用
 48         /// </summary>
 49         public static string ConnString_RW = _connString;
 50         /// <summary>
 51         /// 鏈接字符串 ConnString_R 讀數據庫使用
 52         /// </summary>
 53         public static string ConnString_R = _connString;
 54         /// <summary>
 55         /// DataBaseType Select default:sqlserver
 56         /// </summary>
 57         public static Opt_DataBaseType dataBaseType = Configs.QX_Frame_Helper_DG_Config.DataBaseType;
 58 
 59         #endregion
 60 
 61         static Db_Helper_DG()
 62         {
 63             //if (string.IsNullOrEmpty(ConnString_RW) || string.IsNullOrEmpty(ConnString_R))
 64             //{
 65             //    throw new ArgumentNullException("ConnString Can Not Be Null !");
 66             //}
 67         }
 68 
 69         #region ExcuteNonQuery 執行sql語句或者存儲過程,返回影響的行數---ExcuteNonQuery
 70         /// <summary>
 71         /// 執行sql語句或存儲過程,返回受影響的行數,不帶參數。
 72         /// </summary>
 73         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
 74         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
 75         /// <param name="commandType">命令類型 有默認值CommandType.Text</param>
 76         /// <returns>返回受影響的行數</returns>
 77         public static int ExecuteNonQuery(string commandTextOrSpName, CommandType commandType = CommandType.Text)
 78         {
 79             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_RW))
 80             {
 81                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
 82                 {
 83                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType);
 84                     return cmd.DbCommand.ExecuteNonQuery();
 85                 }
 86             }
 87         }
 88         /// <summary>
 89         /// 執行sql語句或存儲過程,返回受影響的行數。
 90         /// </summary>
 91         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
 92         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
 93         /// <param name="commandType">命令類型 t</param>
 94         /// <param name="parms">SqlParameter[]參數數組,容許空</param>
 95         /// <returns>返回受影響的行數</returns>
 96         public static int ExecuteNonQuery(string commandTextOrSpName, CommandType commandType, params DbParameter[] parms)
 97         {
 98             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_RW))
 99             {
100                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
101                 {
102                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType, parms);//參數增長了commandType 能夠本身編輯執行方式
103                     return cmd.DbCommand.ExecuteNonQuery();
104                 }
105             }
106         }
107         /// <summary>
108         /// 執行sql命令,返回受影響的行數。
109         /// </summary>
110         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
111         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
112         /// <param name="commandType">命令類型</param>
113         /// <param name="obj">object[]參數數組,容許空</param>
114         /// <returns>返回受影響的行數</returns>
115         public static int ExecuteNonQuery(string commandTextOrSpName, CommandType commandType, params object[] obj)
116         {
117             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_RW))
118             {
119                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
120                 {
121                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType, obj);//參數增長了commandType 能夠本身編輯執行方式
122                     return cmd.DbCommand.ExecuteNonQuery();
123                 }
124             }
125         }
126         #endregion
127 
128         #region ExecuteScalar 執行sql語句或者存儲過程,執行單條語句,返回單個結果---ScalarExecuteScalar
129         /// <summary>
130         /// 執行sql語句或存儲過程 返回ExecuteScalar (返回自增的ID)不帶參數
131         /// </summary>
132         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
133         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
134         /// <param name="commandType">命令類型 有默認值CommandType.Text</param>
135         /// <returns></returns>
136         public static object ExecuteScalar(string commandTextOrSpName, CommandType commandType = CommandType.Text)
137         {
138             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW))
139             {
140                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
141                 {
142                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType);
143                     return cmd.DbCommand.ExecuteScalar();
144                 }
145             }
146         }
147         /// <summary>
148         /// 執行sql語句或存儲過程 返回ExecuteScalar (返回自增的ID)
149         /// </summary>
150         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
151         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
152         /// <param name="commandType">命令類型</param>
153         /// <param name="parms">SqlParameter[]參數數組,容許空</param>
154         /// <returns></returns>
155         public static object ExecuteScalar(string commandTextOrSpName, CommandType commandType, params DbParameter[] parms)
156         {
157             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW))
158             {
159                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
160                 {
161                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType, parms);
162                     return cmd.DbCommand.ExecuteScalar();
163                 }
164 
165             }
166         }
167         /// <summary>
168         /// 執行sql語句或存儲過程 返回ExecuteScalar (返回自增的ID)
169         /// </summary>
170         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
171         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
172         /// <param name="commandType">命令類型</param>
173         /// <param name="obj">object[]參數數組,容許空</param>
174         /// <returns></returns>
175         public static object ExecuteScalar(string commandTextOrSpName, CommandType commandType, params object[] obj)
176         {
177             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW))
178             {
179                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
180                 {
181                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType, obj);
182                     return cmd.DbCommand.ExecuteScalar();
183                 }
184             }
185         }
186         #endregion
187 
188         #region ExecuteScalar 執行sql語句或者存儲過程,返回DataReader---DaataReader
189         /// <summary>
190         /// 執行sql語句或存儲過程 返回DataReader 不帶參數
191         /// </summary>
192         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
193         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
194         /// <param name="commandType">命令類型 有默認值CommandType.Text</param>
195         /// <returns></returns>
196         public static DbDataReader ExecuteReader(string commandTextOrSpName, CommandType commandType = CommandType.Text)
197         {
198             //sqlDataReader不能用using 會關閉conn 致使不能獲取到返回值。注意:DataReader獲取值時必須保持鏈接狀態
199             SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW);
200             DbCommandCommon cmd = new DbCommandCommon(dataBaseType);
201             PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType);
202             return cmd.DbCommand.ExecuteReader(CommandBehavior.CloseConnection);
203         }
204         /// <summary>
205         /// 執行sql語句或存儲過程 返回DataReader
206         /// </summary>
207         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
208         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
209         /// <param name="commandType">命令類型</param>
210         /// <param name="parms">SqlParameter[]參數數組,容許空</param>
211         /// <returns></returns>
212         public static DbDataReader ExecuteReader(string commandTextOrSpName, CommandType commandType, params DbParameter[] parms)
213         {
214             //sqlDataReader不能用using 會關閉conn 致使不能獲取到返回值。注意:DataReader獲取值時必須保持鏈接狀態
215             SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW);
216             DbCommandCommon cmd = new DbCommandCommon(dataBaseType);
217             PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType, parms);
218             return cmd.DbCommand.ExecuteReader(CommandBehavior.CloseConnection);
219         }
220         /// <summary>
221         /// 執行sql語句或存儲過程 返回DataReader
222         /// </summary>
223         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
224         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
225         /// <param name="commandType">命令類型</param>
226         /// <param name="obj">object[]參數數組,容許空</param>
227         /// <returns></returns>
228         public static DbDataReader ExecuteReader(string commandTextOrSpName, CommandType commandType, params object[] obj)
229         {
230             //sqlDataReader不能用using 會關閉conn 致使不能獲取到返回值。注意:DataReader獲取值時必須保持鏈接狀態
231             SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW);
232             DbCommandCommon cmd = new DbCommandCommon(dataBaseType);
233             PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType, obj);
234             return cmd.DbCommand.ExecuteReader(CommandBehavior.CloseConnection);
235         }
236         #endregion
237 
238         #region ExecuteDataTable 執行sql語句或者存儲過程,返回一個DataTable---DataTable
239 
240         /**
241          * Update At 2017-3-2 14:58:45
242          * Add the ExecuteDataTable Method into Sql_Helper_DG  
243          **/
244 
245         /// <summary>
246         /// 執行sql語句或存儲過程,返回DataTable不帶參數
247         /// </summary>
248         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
249         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
250         /// <param name="commandType">命令類型 有默認值CommandType.Text</param>
251         /// <returns></returns>
252         public static DataTable ExecuteDataTable(string commandTextOrSpName, CommandType commandType = CommandType.Text)
253         {
254             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW))
255             {
256                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
257                 {
258                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType);
259                     using (DbDataAdapterCommon da = new DbDataAdapterCommon(dataBaseType, cmd.DbCommand))
260                     {
261                         DataSet ds = new DataSet();
262                         da.Fill(ds);
263                         if (ds.Tables.Count > 0)
264                         {
265                             return ds.Tables[0];
266                         }
267                         return default(DataTable);
268                     }
269                 }
270             }
271         }
272         /// <summary>
273         /// 執行sql語句或存儲過程,返回DataTable
274         /// </summary>
275         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
276         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
277         /// <param name="commandType">命令類型</param>
278         /// <param name="parms">SqlParameter[]參數數組,容許空</param>
279         /// <returns></returns>
280         public static DataTable ExecuteDataTable(string commandTextOrSpName, CommandType commandType, params DbParameter[] parms)
281         {
282             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW))
283             {
284                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
285                 {
286                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType, parms);
287                     using (DbDataAdapterCommon da = new DbDataAdapterCommon(dataBaseType, cmd.DbCommand))
288                     {
289                         DataSet ds = new DataSet();
290                         da.Fill(ds);
291                         if (ds.Tables.Count > 0)
292                         {
293                             return ds.Tables[0];
294                         }
295                         return default(DataTable);
296                     }
297                 }
298             }
299         }
300         /// <summary>
301         /// 執行sql語句或存儲過程,返回DataTable
302         /// </summary>
303         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
304         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
305         /// <param name="commandType">命令類型 </param>
306         /// <param name="obj">object[]參數數組,容許空</param>
307         /// <returns></returns>
308         public static DataTable ExecuteDataTable(string commandTextOrSpName, CommandType commandType, params object[] obj)
309         {
310             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW))
311             {
312                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
313                 {
314                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType, obj);
315                     using (DbDataAdapterCommon da = new DbDataAdapterCommon(dataBaseType, cmd.DbCommand))
316                     {
317                         DataSet ds = new DataSet();
318                         da.Fill(ds);
319                         if (ds.Tables.Count > 0)
320                         {
321                             return ds.Tables[0];
322                         }
323                         return default(DataTable);
324                     }
325                 }
326             }
327         }
328         #endregion
329 
330         #region ExecuteDataSet 執行sql語句或者存儲過程,返回一個DataSet---DataSet
331         /// <summary>
332         /// 執行sql語句或存儲過程,返回DataSet 不帶參數
333         /// </summary>
334         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
335         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
336         /// <param name="commandType">命令類型 有默認值CommandType.Text</param>
337         /// <returns></returns>
338         public static DataSet ExecuteDataSet(string commandTextOrSpName, CommandType commandType = CommandType.Text)
339         {
340             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW))
341             {
342                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
343                 {
344                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType);
345                     using (DbDataAdapterCommon da = new DbDataAdapterCommon(dataBaseType, cmd.DbCommand))
346                     {
347                         DataSet ds = new DataSet();
348                         da.Fill(ds);
349                         return ds;
350                     }
351                 }
352             }
353         }
354         /// <summary>
355         /// 執行sql語句或存儲過程,返回DataSet
356         /// </summary>
357         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
358         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
359         /// <param name="commandType">命令類型</param>
360         /// <param name="parms">SqlParameter[]參數數組,容許空</param>
361         /// <returns></returns>
362         public static DataSet ExecuteDataSet(string commandTextOrSpName, CommandType commandType, params DbParameter[] parms)
363         {
364             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW))
365             {
366                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
367                 {
368                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType, parms);
369                     using (DbDataAdapterCommon da = new DbDataAdapterCommon(dataBaseType, cmd.DbCommand))
370                     {
371                         DataSet ds = new DataSet();
372                         da.Fill(ds);
373                         return ds;
374                     }
375                 }
376             }
377         }
378         /// <summary>
379         /// 執行sql語句或存儲過程,返回DataSet
380         /// </summary>
381         /// <param name="ConnString">鏈接字符串,能夠自定義,能夠以使用SqlHelper_DG.ConnString</param>
382         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
383         /// <param name="commandType">命令類型 </param>
384         /// <param name="obj">object[]參數數組,容許空</param>
385         /// <returns></returns>
386         public static DataSet ExecuteDataSet(string commandTextOrSpName, CommandType commandType, params object[] obj)
387         {
388             using (SqlConnection_WR_Safe conn = new SqlConnection_WR_Safe(dataBaseType, ConnString_R, ConnString_RW))
389             {
390                 using (DbCommandCommon cmd = new DbCommandCommon(dataBaseType))
391                 {
392                     PreparCommand(conn.DbConnection, cmd.DbCommand, commandTextOrSpName, commandType, obj);
393                     using (DbDataAdapterCommon da = new DbDataAdapterCommon(dataBaseType, cmd.DbCommand))
394                     {
395                         DataSet ds = new DataSet();
396                         da.Fill(ds);
397                         return ds;
398                     }
399                 }
400             }
401         }
402         #endregion
403 
404         #region ExecuteList Entity 執行sql語句或者存儲過程,返回一個List<T>---List<T>
405         public static List<Entity> ExecuteList<Entity>(string commandTextOrSpName, CommandType commandType = CommandType.Text) where Entity : class
406         {
407             return GetListFromDataSet<Entity>(ExecuteDataSet(commandTextOrSpName, commandType));
408         }
409         public static List<Entity> ExecuteList<Entity>(string commandTextOrSpName, CommandType commandType, params DbParameter[] parms) where Entity : class
410         {
411             return GetListFromDataSet<Entity>(ExecuteDataSet(commandTextOrSpName, commandType, parms));
412         }
413         public static List<Entity> ExecuteList<Entity>(string commandTextOrSpName, CommandType commandType, params object[] obj) where Entity : class
414         {
415             return GetListFromDataSet<Entity>(ExecuteDataSet(commandTextOrSpName, commandType, obj));
416         }
417         #endregion
418 
419         #region ExecuteEntity 執行sql語句或者存儲過程,返回一個Entity---Entity
420         public static Entity ExecuteEntity<Entity>(string commandTextOrSpName, CommandType commandType = CommandType.Text) where Entity : class
421         {
422             return GetEntityFromDataSet<Entity>(ExecuteDataSet(commandTextOrSpName, commandType));
423         }
424         public static Entity ExecuteEntity<Entity>(string commandTextOrSpName, CommandType commandType, params DbParameter[] parms) where Entity : class
425         {
426             return GetEntityFromDataSet<Entity>(ExecuteDataSet(commandTextOrSpName, commandType, parms));
427         }
428         public static Entity ExecuteEntity<Entity>(string commandTextOrSpName, CommandType commandType, params object[] obj) where Entity : class
429         {
430             return GetEntityFromDataSet<Entity>(ExecuteDataSet(commandTextOrSpName, commandType, obj));
431         }
432         #endregion
433 
434         #region ---PreparCommand 構建一個通用的command對象供內部方法進行調用---
435         /// <summary>
436         /// 不帶參數的設置sqlcommand對象
437         /// </summary>
438         /// <param name="conn">sqlconnection對象</param>
439         /// <param name="cmd">sqlcommmand對象</param>
440         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
441         /// <param name="commandType">語句的類型</param>
442         private static void PreparCommand(DbConnection conn, DbCommand cmd, string commandTextOrSpName, CommandType commandType)
443         {
444             //打開鏈接
445             if (conn.State != ConnectionState.Open)
446             {
447                 conn.Open();
448             }
449 
450             //設置SqlCommand對象的屬性值
451             cmd.Connection = conn;
452             cmd.CommandType = commandType;
453             cmd.CommandText = commandTextOrSpName;
454             cmd.CommandTimeout = 60;
455         }
456         /// <summary>
457         /// 設置一個等待執行的SqlCommand對象
458         /// </summary>
459         /// <param name="conn">sqlconnection對象</param>
460         /// <param name="cmd">sqlcommmand對象</param>
461         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
462         /// <param name="commandType">語句的類型</param>
463         /// <param name="parms">參數,sqlparameter類型,須要指出全部的參數名稱</param>
464         private static void PreparCommand(DbConnection conn, DbCommand cmd, string commandTextOrSpName, CommandType commandType, params SqlParameter[] parms)
465         {
466             //打開鏈接
467             if (conn.State != ConnectionState.Open)
468             {
469                 conn.Open();
470             }
471 
472             //設置SqlCommand對象的屬性值
473             cmd.Connection = conn;
474             cmd.CommandType = commandType;
475             cmd.CommandText = commandTextOrSpName;
476             cmd.CommandTimeout = 60;
477 
478             if (parms != null)
479             {
480                 cmd.Parameters.Clear();
481                 cmd.Parameters.AddRange(parms);
482             }
483         }
484         /// <summary>
485         /// PreparCommand方法,可變參數爲object須要嚴格按照參數順序傳參
486         /// 之因此會用object參數方法是爲了咱們能更方便的調用存儲過程,沒必要去關係存儲過程參數名是什麼,知道它的參數順序就能夠了 sqlparameter必須指定每個參數名稱
487         /// </summary>
488         /// <param name="conn">sqlconnection對象</param>
489         /// <param name="cmd">sqlcommmand對象</param>
490         /// <param name="commandTextOrSpName">sql語句或存儲過程名稱</param>
491         /// <param name="commandType">語句的類型</param>
492         /// <param name="parms">參數,object類型,須要按順序賦值</param>
493         private static void PreparCommand(DbConnection conn, DbCommand cmd, string commandTextOrSpName, CommandType commandType, params object[] parms)
494         {
495             //打開鏈接
496             if (conn.State != ConnectionState.Open)
497             {
498                 conn.Open();
499             }
500 
501             //設置SqlCommand對象的屬性值
502             cmd.Connection = conn;
503             cmd.CommandType = commandType;
504             cmd.CommandText = commandTextOrSpName;
505             cmd.CommandTimeout = 60;
506 
507             cmd.Parameters.Clear();
508             if (parms != null)
509             {
510                 cmd.Parameters.AddRange(parms);
511             }
512         }
513         #endregion
514 
515         #region 經過Model反射返回結果集 Model爲 Entity 泛型變量的真實類型---反射返回結果集
516         /// <summary>
517         /// 反射返回一個List T 類型的結果集
518         /// </summary>
519         /// <typeparam name="T">Model中對象類型</typeparam>
520         /// <param name="ds">DataSet結果集</param>
521         /// <returns></returns>
522         public static List<Entity> GetListFromDataSet<Entity>(DataSet ds) where Entity : class
523         {
524             List<Entity> list = new List<Entity>();//實例化一個list對象
525             PropertyInfo[] propertyInfos = typeof(Entity).GetProperties();     //獲取T對象的全部公共屬性
526 
527             DataTable dt = ds.Tables[0];    // 獲取到ds的dt
528             if (dt.Rows.Count > 0)
529             {
530                 //判斷讀取的行是否>0 即數據庫數據已被讀取
531                 foreach (DataRow row in dt.Rows)
532                 {
533                     Entity model1 = System.Activator.CreateInstance<Entity>();//實例化一個對象,便於往list裏填充數據
534                     foreach (PropertyInfo propertyInfo in propertyInfos)
535                     {
536                         try
537                         {
538                             //遍歷模型裏全部的字段
539                             if (row[propertyInfo.Name] != System.DBNull.Value)
540                             {
541                                 //判斷值是否爲空,若是空賦值爲null見else
542                                 if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
543                                 {
544                                     //若是convertsionType爲nullable類,聲明一個NullableConverter類,該類提供從Nullable類到基礎基元類型的轉換
545                                     NullableConverter nullableConverter = new NullableConverter(propertyInfo.PropertyType);
546                                     //將convertsionType轉換爲nullable對的基礎基元類型
547                                     propertyInfo.SetValue(model1, Convert.ChangeType(row[propertyInfo.Name], nullableConverter.UnderlyingType), null);
548                                 }
549                                 else
550                                 {
551                                     propertyInfo.SetValue(model1, Convert.ChangeType(row[propertyInfo.Name], propertyInfo.PropertyType), null);
552                                 }
553                             }
554                             else
555                             {
556                                 propertyInfo.SetValue(model1, null, null);//若是數據庫的值爲空,則賦值爲null
557                             }
558                         }
559                         catch (Exception)
560                         {
561                             propertyInfo.SetValue(model1, null, null);//若是數據庫的值爲空,則賦值爲null
562                         }
563                     }
564                     list.Add(model1);//將對象填充到list中
565                 }
566             }
567             return list;
568         }
569         /// <summary>
570         /// 反射返回一個T類型的結果
571         /// </summary>
572         /// <typeparam name="T">Model中對象類型</typeparam>
573         /// <param name="reader">SqlDataReader結果集</param>
574         /// <returns></returns>
575         public static Entity GetEntityFromDataReader<Entity>(DbDataReader reader) where Entity : class
576         {
577             Entity model = System.Activator.CreateInstance<Entity>();           //實例化一個T類型對象
578             PropertyInfo[] propertyInfos = model.GetType().GetProperties();     //獲取T對象的全部公共屬性
579             using (reader)
580             {
581                 if (reader.Read())
582                 {
583                     foreach (PropertyInfo propertyInfo in propertyInfos)
584                     {
585                         //遍歷模型裏全部的字段
586                         if (reader[propertyInfo.Name] != System.DBNull.Value)
587                         {
588                             //判斷值是否爲空,若是空賦值爲null見else
589                             if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
590                             {
591                                 //若是convertsionType爲nullable類,聲明一個NullableConverter類,該類提供從Nullable類到基礎基元類型的轉換
592                                 NullableConverter nullableConverter = new NullableConverter(propertyInfo.PropertyType);
593                                 //將convertsionType轉換爲nullable對的基礎基元類型
594                                 propertyInfo.SetValue(model, Convert.ChangeType(reader[propertyInfo.Name], nullableConverter.UnderlyingType), null);
595                             }
596                             else
597                             {
598                                 propertyInfo.SetValue(model, Convert.ChangeType(reader[propertyInfo.Name], propertyInfo.PropertyType), null);
599                             }
600                         }
601                         else
602                         {
603                             propertyInfo.SetValue(model, null, null);//若是數據庫的值爲空,則賦值爲null
604                         }
605                     }
606                     return model;//返回T類型的賦值後的對象 model
607                 }
608             }
609             return default(Entity);//返回引用類型和值類型的默認值0或null
610         }
611         /// <summary>
612         /// 反射返回一個T類型的結果
613         /// </summary>
614         /// <typeparam name="T">Model中對象類型</typeparam>
615         /// <param name="ds">DataSet結果集</param>
616         /// <returns></returns>
617         public static Entity GetEntityFromDataSet<Entity>(DataSet ds) where Entity : class
618         {
619             return GetListFromDataSet<Entity>(ds).FirstOrDefault();
620         }
621         #endregion
622     }
623     /**
624     * author:qixiao
625     * time:2017-9-18 18:02:23
626     * description:safe create sqlconnection support
627     * */
628     internal class SqlConnection_WR_Safe : IDisposable
629     {
630         /// <summary>
631         /// SqlConnection
632         /// </summary>
633         public DbConnection DbConnection { get; set; }
634 
635         public SqlConnection_WR_Safe(Opt_DataBaseType dataBaseType, string ConnString_RW)
636         {
637             this.DbConnection = GetDbConnection(dataBaseType, ConnString_RW);
638         }
639         /**
640          * if read db disabled,switchover to read write db immediately
641          * */
642         public SqlConnection_WR_Safe(Opt_DataBaseType dataBaseType, string ConnString_R, string ConnString_RW)
643         {
644             try
645             {
646                 this.DbConnection = GetDbConnection(dataBaseType, ConnString_R);
647             }
648             catch (Exception)
649             {
650                 this.DbConnection = GetDbConnection(dataBaseType, ConnString_RW);
651             }
652         }
653 
654         /// <summary>
655         /// GetDataBase ConnectionString by database type and connection string -- private use
656         /// </summary>
657         /// <param name="dataBaseType"></param>
658         /// <param name="ConnString"></param>
659         /// <returns></returns>
660         private DbConnection GetDbConnection(Opt_DataBaseType dataBaseType, string ConnString)
661         {
662             switch (dataBaseType)
663             {
664                 case Opt_DataBaseType.SqlServer:
665                     return new SqlConnection(ConnString);
666                 case Opt_DataBaseType.MySql:
667                     return new MySqlConnection(ConnString);
668                 case Opt_DataBaseType.Oracle:
669                     return new OracleConnection(ConnString);
670                 default:
671                     return new SqlConnection(ConnString);
672             }
673         }
674         /// <summary>
675         /// Must Close Connection after use
676         /// </summary>
677         public void Dispose()
678         {
679             if (this.DbConnection != null)
680             {
681                 this.DbConnection.Dispose();
682             }
683         }
684     }
685     /// <summary>
686     /// Common sqlcommand
687     /// </summary>
688     internal class DbCommandCommon : IDisposable
689     {
690         /// <summary>
691         /// common dbcommand
692         /// </summary>
693         public DbCommand DbCommand { get; set; }
694         public DbCommandCommon(Opt_DataBaseType dataBaseType)
695         {
696             this.DbCommand = GetDbCommand(dataBaseType);
697         }
698 
699         /// <summary>
700         /// Get DbCommand select database type
701         /// </summary>
702         /// <param name="dataBaseType"></param>
703         /// <returns></returns>
704         private DbCommand GetDbCommand(Opt_DataBaseType dataBaseType)
705         {
706             switch (dataBaseType)
707             {
708                 case Opt_DataBaseType.SqlServer:
709                     return new SqlCommand();
710                 case Opt_DataBaseType.MySql:
711                     return new MySqlCommand();
712                 case Opt_DataBaseType.Oracle:
713                     return new OracleCommand();
714                 default:
715                     return new SqlCommand();
716             }
717         }
718         /// <summary>
719         /// must dispose after use
720         /// </summary>
721         public void Dispose()
722         {
723             if (this.DbCommand != null)
724             {
725                 this.DbCommand.Dispose();
726             }
727         }
728     }
729     /// <summary>
730     /// DbDataAdapterCommon
731     /// </summary>
732     internal class DbDataAdapterCommon : DbDataAdapter, IDisposable
733     {
734         public DbDataAdapter DbDataAdapter { get; set; }
735         public DbDataAdapterCommon(Opt_DataBaseType dataBaseType, DbCommand dbCommand)
736         {
737             //get dbAdapter
738             this.DbDataAdapter = GetDbAdapter(dataBaseType, dbCommand);
739             //provid select command
740             this.SelectCommand = dbCommand;
741         }
742         private DbDataAdapter GetDbAdapter(Opt_DataBaseType dataBaseType, DbCommand dbCommand)
743         {
744             switch (dataBaseType)
745             {
746                 case Opt_DataBaseType.SqlServer:
747                     return new SqlDataAdapter();
748                 case Opt_DataBaseType.MySql:
749                     return new MySqlDataAdapter();
750                 case Opt_DataBaseType.Oracle:
751                     return new OracleDataAdapter();
752                 default:
753                     return new SqlDataAdapter();
754             }
755         }
756         /// <summary>
757         /// must dispose after use
758         /// </summary>
759         public new void Dispose()
760         {
761             if (this.DbDataAdapter != null)
762             {
763                 this.DbDataAdapter.Dispose();
764             }
765         }
766     }
767 }
Db_Helper_DG

  Db_Helper_DG簡介:

  本類分爲 ExecuteNonQuery、ExecuteScalar、ExecuteScalar、ExecuteDataTable、ExecuteDataSet、ExecuteList Entity、ExecuteEntity七大部分,每一部分分爲 無條件參數執行Sql語句或存儲過程、SqlParameter[]參數執行Sql語句,Object[]參數執行存儲過程三個重載方法。

  方法的詳細代碼見上一條主代碼Db_Helper_DG中摺疊部分,這裏對ExecuteListEntity和ExecuteEntity方法進行着重介紹。

  ExecuteListEntity和ExecuteEntity,此二方法是爲了將查詢結果和Model即Entity實體進行映射所用,使用C#反射Reflect技術,進行將查詢結果直接賦值成爲了Entity或者List<Entity>對象(此亦是ORM框架的核心)

  ExecuteList方法經過二次封裝,顯式調用GetListFromDataSet方法,從DataSet結果集中遍歷結果以進行賦值,代碼以下:

 1 public static List<Entity> GetListFromDataSet<Entity>(DataSet ds) where Entity : class
 2         {
 3             List<Entity> list = new List<Entity>();//實例化一個list對象
 4             PropertyInfo[] propertyInfos = typeof(Entity).GetProperties();     //獲取T對象的全部公共屬性
 5 
 6             DataTable dt = ds.Tables[0];    // 獲取到ds的dt
 7             if (dt.Rows.Count > 0)
 8             {
 9                 //判斷讀取的行是否>0 即數據庫數據已被讀取
10                 foreach (DataRow row in dt.Rows)
11                 {
12                     Entity model1 = System.Activator.CreateInstance<Entity>();//實例化一個對象,便於往list裏填充數據
13                     foreach (PropertyInfo propertyInfo in propertyInfos)
14                     {
15                         try
16                         {
17                             //遍歷模型裏全部的字段
18                             if (row[propertyInfo.Name] != System.DBNull.Value)
19                             {
20                                 //判斷值是否爲空,若是空賦值爲null見else
21                                 if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
22                                 {
23                                     //若是convertsionType爲nullable類,聲明一個NullableConverter類,該類提供從Nullable類到基礎基元類型的轉換
24                                     NullableConverter nullableConverter = new NullableConverter(propertyInfo.PropertyType);
25                                     //將convertsionType轉換爲nullable對的基礎基元類型
26                                     propertyInfo.SetValue(model1, Convert.ChangeType(row[propertyInfo.Name], nullableConverter.UnderlyingType), null);
27                                 }
28                                 else
29                                 {
30                                     propertyInfo.SetValue(model1, Convert.ChangeType(row[propertyInfo.Name], propertyInfo.PropertyType), null);
31                                 }
32                             }
33                             else
34                             {
35                                 propertyInfo.SetValue(model1, null, null);//若是數據庫的值爲空,則賦值爲null
36                             }
37                         }
38                         catch (Exception)
39                         {
40                             propertyInfo.SetValue(model1, null, null);//若是數據庫的值爲空,則賦值爲null
41                         }
42                     }
43                     list.Add(model1);//將對象填充到list中
44                 }
45             }
46             return list;
47         }

  ExecuteEntity部分又分爲從DataReader中獲取和Linq從List<Entity>獲取第一條進行獲取兩種方式,因爲DataReader有佔用鏈接不釋放的特色,在高併發的環境下使用並不友好,所以在實際生產環境中使用推薦使用第二種Linq獲取List<Entity>的方式:

 1 public static Entity GetEntityFromDataReader<Entity>(DbDataReader reader) where Entity : class
 2         {
 3             Entity model = System.Activator.CreateInstance<Entity>();           //實例化一個T類型對象
 4             PropertyInfo[] propertyInfos = model.GetType().GetProperties();     //獲取T對象的全部公共屬性
 5             using (reader)
 6             {
 7                 if (reader.Read())
 8                 {
 9                     foreach (PropertyInfo propertyInfo in propertyInfos)
10                     {
11                         //遍歷模型裏全部的字段
12                         if (reader[propertyInfo.Name] != System.DBNull.Value)
13                         {
14                             //判斷值是否爲空,若是空賦值爲null見else
15                             if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
16                             {
17                                 //若是convertsionType爲nullable類,聲明一個NullableConverter類,該類提供從Nullable類到基礎基元類型的轉換
18                                 NullableConverter nullableConverter = new NullableConverter(propertyInfo.PropertyType);
19                                 //將convertsionType轉換爲nullable對的基礎基元類型
20                                 propertyInfo.SetValue(model, Convert.ChangeType(reader[propertyInfo.Name], nullableConverter.UnderlyingType), null);
21                             }
22                             else
23                             {
24                                 propertyInfo.SetValue(model, Convert.ChangeType(reader[propertyInfo.Name], propertyInfo.PropertyType), null);
25                             }
26                         }
27                         else
28                         {
29                             propertyInfo.SetValue(model, null, null);//若是數據庫的值爲空,則賦值爲null
30                         }
31                     }
32                     return model;//返回T類型的賦值後的對象 model
33                 }
34             }
35             return default(Entity);//返回引用類型和值類型的默認值0或null
36         }
1 public static Entity GetEntityFromDataSet<Entity>(DataSet ds) where Entity : class
2         {
3             return GetListFromDataSet<Entity>(ds).FirstOrDefault();
4         }

【系統測試】

   在所有功能實現之餘,下面咱們進行代碼測試環節。

  一、MySql數據庫操做

  

  各類方式給Db_Helper_DG的連接字符串屬性進行賦值,這裏再也不贅述。

   

  

  根據測試表的設計進行新建對應的實體類:

1 public class TB_People
2     {
3         public Guid Uid { get; set; }
4         public string Name { get; set; }
5         public int Age { get; set; }
6         public int ClassId { get; set; }
7     }

  

  填寫好鏈接字符串,並給Db_Helper_DG類的ConnString_Default屬性賦值後,咱們直接調用方法進行查詢操做。

  

  調用靜態方法ExecuteList以便直接映射到實體類:

1 List<TB_People> peopleList = Db_Helper_DG.ExecuteList<TB_People>("select * from student where ClassId=?ClassId", System.Data.CommandType.Text, new MySqlParameter("?ClassId", 1));
2             foreach (var item in peopleList)
3             {
4                 Console.WriteLine(item.Name);
5             }

   

  這裏的MySql語句 select * from student where ClassId=?ClassId 而後參數化賦值 ?ClassId=1 進行查詢。

  結果以下:

  

  可見,查詢結果並沒有任何差池,自動映射到了實體類的屬性。

  二、SqlServer數據庫操做

  

  由於數據庫結構MySql和SqlServer的結構是一致的,所以使用上述的實體類TB_People。

  

   一樣填寫鏈接字符串,並給Db_Helper_DG類的ConnString_Default屬性賦值後,咱們直接調用方法進行查詢操做。

  

  

  而後咱們修改Sql語句,而且修改成SqlServer傳遞參數方式進行查詢:

   

1 List<TB_People> peopleList = Db_Helper_DG.ExecuteList<TB_People>("select * from TB_People where ClassId=@ClassId", System.Data.CommandType.Text, new SqlParameter("@ClassId", 1));
2 foreach (var item in peopleList)
3 {
4     Console.WriteLine(item.Name);
5 }

  select * from TB_People where ClassId =1,ClassId按照SqlServer參數傳遞的方式進行傳遞。

  

   可見,查詢結果並沒有任何差池,自動映射到了實體類的屬性。

  三、Oracle因爲本人當前Oracle環境問題,先不進行測試。

相關文章
相關標籤/搜索