当前位置:Gxlcms > 数据库问题 > C#操作SqlServer MySql Oracle通用帮助类Db_Helper_DG(默认支持数据库读写分离、查询结果实体映射ORM)

C#操作SqlServer MySql Oracle通用帮助类Db_Helper_DG(默认支持数据库读写分离、查询结果实体映射ORM)

时间:2021-07-01 10:21:17 帮助过:13人阅读

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 }

 全部代码见此:

  1、数据库选择器枚举类: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

  2、主类代码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 ExecuteReader 执行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         /// 
                        
                    

人气教程排行