您的位置:首页 > 博客中心 > 数据库 >

面向对象编程、模块内高内聚、模块间低耦合、数据库操作工具类

时间:2022-03-15 15:13

一、web.config帮助类(ConfigHelper.cs)

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Configuration;
  4 using System.Reflection;
  5 
  6 namespace Common
  7 {
  8     /// <summary>
  9     /// web.config操作类
 10     /// author:陈彦斌
 11     /// 时间:2019年7月14日23:32:08
 12     /// 使用前需引用程序集:System.configuration
 13     /// </summary>
 14     public sealed class ConfigHelper
 15     {
 16         /// <summary>
 17         /// 获取系统配置信息
 18         /// </summary>
 19         /// <typeparam name="SystemConfig"></typeparam>
 20         /// <returns></returns>
 21         public static SystemConfig GetAppSettingsAllInfo()
 22         {
 23             try
 24             {
 25                 SystemConfig t = new SystemConfig();
 26                 string[] arrSysCfg = ConfigurationManager.AppSettings.AllKeys;
 27                 string value = string.Empty;
 28                 foreach (var key in arrSysCfg)
 29                 {
 30                     value = CacheHelper.GetAppSettings(key).ToString();
 31                     foreach (PropertyInfo pi in t.GetType().GetProperties())
 32                     {
 33                         if (key.Contains(pi.Name))
 34                         {
 35                             if (!StringUtil.isNullOrBlank(value))
 36                             {
 37                                 pi.SetValue(t, value, null);
 38                             }
 39                         }
 40                     }
 41                 }
 42                 return t;
 43             }
 44             catch(Exception ex)
 45             {
 46                 throw ex; 
 47             }
 48         }
 49         /// <summary>
 50         /// 获取链接字符串
 51         /// </summary>
 52         /// <param name="key"></param>
 53         /// <returns></returns>
 54         public static string GetConnectionString(string key)
 55         {
 56             return ConfigurationManager.ConnectionStrings[key].ConnectionString;
 57         }
 58         /// <summary>
 59         /// 获取AppSettings中配置String信息
 60         /// </summary>
 61         /// <param name="key">键</param>
 62         /// <returns></returns>
 63         public static string GetConfigString(string key)
 64         {
 65             object objValue = CacheHelper.GetCache(key);
 66             if (objValue == null) //缓冲区没有值
 67             {
 68                 objValue = CacheHelper.GetAppSettings(key);
 69                 if (objValue != null)
 70                 {
 71                     CacheHelper.SetCache(key, objValue, DateTime.Now.AddMinutes(180), TimeSpan.Zero);
 72                 }
 73             }
 74             return objValue.ToString();
 75         }
 76         /// <summary>
 77         /// 获取AppSettings中配置Bool信息
 78         /// </summary>
 79         /// <param name="key">键</param>
 80         /// <returns></returns>
 81         public static bool GetConfigBool(string key)
 82         {
 83             object objValue= CacheHelper.GetAppSettings(key);
 84             if (StringUtil.isNullOrBlank(objValue))
 85             {
 86                 try
 87                 {
 88                     bool.Parse(objValue.ToString());
 89                     return true;
 90                 }
 91                 catch
 92                 {
 93                     return false;
 94                 }
 95             }
 96             return false;
 97         }
 98         /// <summary>
 99         /// 获取AppSettings中配置decimal信息
100         /// </summary>
101         /// <param name="key"></param>
102         /// <returns></returns>
103         public static decimal GetConfigDecimal(string key)
104         {
105             object objValue = CacheHelper.GetAppSettings(key);
106             if (StringUtil.isNullOrBlank(objValue))
107             {
108                 try
109                 {                    
110                     return decimal.Parse(objValue.ToString());
111                 }
112                 catch
113                 {
114                     return 0;
115                 }
116             }
117             return 0;
118         }
119         /// <summary>
120         /// 获取AppSettings中配置DateTime信息,可空
121         /// </summary>
122         /// <param name="key">键</param>
123         /// <returns></returns>
124         public static DateTime? GetConfigDateTime(string key)
125         {
126             DateTime? DateTimeNull = null;
127             object objValue = CacheHelper.GetAppSettings(key);
128             if (StringUtil.isNullOrBlank(objValue))
129             {
130                 try
131                 {
132                     return DateTime.Parse(objValue.ToString());
133                 }
134                 catch
135                 {
136                     return DateTimeNull;
137                 }
138             }
139             return DateTimeNull;
140         }
141     }
142     /// <summary>
143     /// 系统配置类
144     /// </summary>
145     public sealed class SystemConfig
146     {
147         /// <summary>
148         /// 数据库连接字符串
149         /// </summary>
150         public string ConnectionString { get; set; }
151         /// <summary>
152         /// 数据库类型
153         /// </summary>
154         public string dbType { get; set; }
155         /// <summary>
156         /// 打印报错SQL语句物理路径
157         /// </summary>
158         public string PrintErrorSqlPath { get; set; }
159         /// <summary>
160         /// 是否打印
161         /// </summary>
162         public string IsPrint { get; set; }
163     }
164 }

二、缓存帮助类(CacheHelper.cs)

 1 using System;
 2 using System.Collections;
 3 using System.Configuration;
 4 using System.Web;
 5 using System.Web.Caching;
 6 
 7 namespace Common
 8 {
 9     /// <summary>
10     /// 缓存帮助类
11     /// author:陈彦斌
12     /// 时间:2019年7月14日14:25:30
13     /// HttpRuntime.Cache
14     /// </summary>
15     public sealed class CacheHelper
16     {
17         /// <summary>
18         /// 获取configuratio节点下appSettings中add的值
19         /// </summary>
20         /// <param name="key">AppSettings的键</param>
21         /// <returns></returns>
22         public static object GetAppSettings(string key)
23         {
24             return ConfigurationManager.AppSettings[key];
25         }
26         /// <summary>
27         /// 获取当前应用程序指定CacheKey的值
28         /// </summary>
29         /// <param name="CacheKey">appSettings节点下add中的键</param>
30         /// <returns></returns>
31         public static object GetCache(string CacheKey)
32         {
33             Cache objCache = HttpRuntime.Cache;
34             return objCache[CacheKey];
35         }
36         /// <summary>
37         /// 设置数据缓存(慎用)
38         /// </summary>
39         /// <param name="CacheKey">键</param>
40         /// <param name="CacheValue">值</param>
41         public static void SetCache(string CacheKey,object CacheValue)
42         {
43             Cache objCache = HttpRuntime.Cache;
44             objCache.Insert(CacheKey, CacheValue);
45         }
46         /// <summary>
47         /// 设置数据缓存
48         /// </summary>
49         /// <param name="CacheKey">键</param>
50         /// <param name="CacheValue">值</param>
51         /// <param name="TimeOut">时间间隔</param>
52         public static void SetCache(string CacheKey, object CacheValue, TimeSpan TimeOut)
53         {
54             Cache objCache = HttpRuntime.Cache;
55             objCache.Insert(CacheKey, CacheValue, null, DateTime.MaxValue, TimeOut, CacheItemPriority.NotRemovable, null);
56         }
57         /// <summary>
58         /// 设置数据缓存
59         /// </summary>
60         /// <param name="CacheKey">键</param>
61         /// <param name="CacheValue">值</param>
62         /// <param name="absoluteExpiration">绝对过期时间</param>
63         /// <param name="slidingExpiration">时间间隔</param>
64         public static void SetCache(string CacheKey, object CacheValue, DateTime absoluteExpiration, TimeSpan slidingExpiration)
65         {
66             Cache objCache = HttpRuntime.Cache;
67             objCache.Insert(CacheKey, CacheValue, null, absoluteExpiration, slidingExpiration);
68         }
69         /// <summary>
70         /// 移除全部缓存
71         /// </summary>
72         public static void RemovaAllCache()
73         {
74             Cache objCache = HttpRuntime.Cache;
75             IDictionaryEnumerator CacheEnum = objCache.GetEnumerator();
76             while (CacheEnum.MoveNext())
77             {
78                 objCache.Remove(CacheEnum.Key.ToString());
79             }
80         }
81         /// <summary>
82         /// 移除指定键的缓存
83         /// </summary>
84         /// <param name="CacheKey">键</param>
85         public static void RemovaAllCache(string CacheKey)
86         {
87             Cache objCache = HttpRuntime.Cache;
88             objCache.Remove(CacheKey);
89         }
90     }
91 }

三、数据库基类(DbBaseTool.cs)

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Text;
  4 using System.IO;
  5 using System.Data.Common;
  6 using System.Data;
  7 using System.Data.SqlClient;
  8 using System.Data.OracleClient;
  9 using System.Threading;
 10 
 11 namespace Tool
 12 {
 13     /// <summary>
 14     /// 操作数据库基类
 15     /// author:陈彦斌
 16     /// 时间:2019年7月14日23:35:30
 17     /// </summary>
 18     public abstract class DbBaseTool
 19     {
 20         public const string c_where = " WHERE ";
 21         public const string c_where_one_equal_one = " WHERE 1=1 ";
 22         public const string c_where_one_equal_one_and = " WHERE 1=1 AND ";
 23         public const string c_like = " LIKE ";
 24         public const string c_and = " AND ";
 25         public const string c_or = " OR ";
 26         public const string c_equal = " = ";
 27         public const char c_comma_split = ‘,‘;
 28     }
 29     /// <summary>
 30     /// 错误信息打印类
 31     /// author:陈彦斌
 32     /// 时间:2019年7月14日23:36:10
 33     /// </summary>
 34     public class PrintSqlTool
 35     {
 36         public static string LogBasePath { get; set; }
 37         public static Queue<string> execSqlQueue = new Queue<string>();
 38         private const string printTxtSqlTemp = "打印时间:{0}\r\nSQL语句:\r\n      {1}\r\n";
 39         static PrintSqlTool()
 40         {
 41             ThreadPool.QueueUserWorkItem(o =>
 42             {
 43                 while (true)
 44                 {
 45                     lock (execSqlQueue)
 46                     {
 47                         if (execSqlQueue.Count > 0)
 48                         {
 49                             PrintSqlToText(LogBasePath,execSqlQueue.Dequeue());
 50                         }
 51                     }
 52                 }
 53             });
 54         }
 55         /// <summary>
 56         /// 打印报错SQL语句
 57         /// </summary>
 58         /// <param name="strPath">物理绝对路径</param>
 59         /// <param name="sql">报错SQL语句</param>
 60         public static void PrintSqlToText(string strPath, string sql)
 61         {
 62             appendStrToTxtFile(strPath, sql);
 63         }
 64         /// <summary>
 65         /// 打印报错SQL语句
 66         /// </summary>
 67         /// <param name="strPath">物理绝对路径</param>
 68         /// <param name="list">报错SQL语句集合</param>
 69         public static void PrintSqlToText(string strPath, List<string> list)
 70         {
 71             StringBuilder sb = new StringBuilder();
 72             foreach (var item in list)
 73             {
 74                 sb.Append(item).Append(";");
 75             }
 76             appendStrToTxtFile(strPath, sb.ToString().TrimEnd(‘,‘));
 77         }
 78         /// <summary>
 79         /// 向文本追加字符串
 80         /// </summary>
 81         /// <param name="fileFullPath">物理绝对路径</param>
 82         /// <param name="errStr">报错语句</param>
 83         private static void appendStrToTxtFile(string fileFullPath, string errStr)
 84         {
 85             FileStream fs = null; //文件流
 86             StreamWriter sw = null; //写入流
 87             try
 88             {
 89                 if (File.Exists(fileFullPath)) //判断文件是否存在
 90                 {
 91                     fs = new FileStream(fileFullPath, FileMode.Append); //打开文件搜寻到文件尾
 92                 }
 93                 else
 94                 {
 95                     fs = new FileStream(fileFullPath, FileMode.Create); //创建文件
 96                 }
 97                 sw = new StreamWriter(fs, Encoding.UTF8); //指定写入格式
 98                 sw.Write(string.Format(printTxtSqlTemp,DateTime.Now.ToString(), errStr)); //写入
 99             }
100             catch (UnauthorizedAccessException err)
101             {
102                 throw err;
103             }
104             catch (IOException err)
105             {
106                 throw err;
107             }
108             finally
109             {
110                 if (sw != null)
111                 {
112                     sw.Close();
113                 }
114                 if (fs != null)
115                 {
116                     fs.Close();
117                 }
118             }
119         }
120     }
121     /// <summary>
122     /// 数据接口类
123     /// author:陈彦斌
124     /// 时间:2019年7月14日23:36:51
125     /// </summary>
126     public interface IDbProvider
127     {
128         /// <summary>
129         /// 连接字符串
130         /// </summary>
131         string connStr { get; set; }
132         /// <summary>
133         /// 初始化 IDbConnection 类的新实例。
134         /// </summary>
135         /// <returns></returns>
136         IDbConnection GetConnection();
137         /// <summary>
138         /// 如果给定包含连接字符串的字符串,则初始化 IDbConnection 类的新实例。
139         /// </summary>
140         /// <param name="connectionString">用于打开 SQL Server 数据库的连接。</param>
141         /// <returns></returns>
142         IDbConnection GetConnection(string connectionString);
143         /// <summary>
144         /// 初始化 IDbCommand 类的新实例。
145         /// </summary>
146         /// <returns></returns>
147         IDbCommand GetCommand();
148         /// <summary>
149         /// 用查询文本初始化 IDbCommand 类的新实例。
150         /// </summary>
151         /// <param name="cmdText">查询的文本。</param>
152         /// <returns></returns>
153         IDbCommand GetCommand(string cmdText);
154         /// <summary>
155         /// 初始化 IDbCommand 类的新实例。
156         /// </summary>
157         /// <param name="connection">数据库链接字符串</param>
158         /// <param name="transaction">将在其中执行 IDbCommand 的 IDbTransaction。</param>
159         /// <returns></returns>
160         IDbCommand GetCommand(IDbConnection connection, IDbTransaction transaction);
161         /// <summary>
162         /// 初始化具有查询文本和 IDbConnection 的 IDbCommand类的新实例。
163         /// </summary>
164         /// <param name="cmdText">查询的文本。</param>
165         /// <param name="connection">数据库链接字符串</param>
166         /// <returns></returns>
167         IDbCommand GetCommand(string cmdText, IDbConnection connection);
168         /// <summary>
169         /// 初始化 IDbCommand 类的新实例。
170         /// </summary>
171         /// <param name="cmdText">查询的文本。</param>
172         /// <param name="connection">数据库链接字符串</param>
173         /// <param name="transaction">将在其中执行 IDbCommand 的 IDbTransaction。</param>
174         /// <returns></returns>
175         IDbCommand GetCommand(string cmdText, IDbConnection connection, IDbTransaction transaction);
176         /// <summary>
177         /// 初始化 DbDataAdapter 类的新实例。
178         /// </summary>
179         /// <returns></returns>
180         DbDataAdapter GetDataAdapter();
181         /// <summary>
182         /// 初始化 DbDataAdapter 类的新实例,用指定的 DbDataAdapter 作为 DbDataAdapter.SelectCommand 的属性
183         /// </summary>
184         /// <param name="selectCommand">一个 IDbCommand(可以是 Transact-SQL SELECT 语句或存储过程),已设置为 DbDataAdapter 的 IDbCommand 属性。</param>
185         /// <returns></returns>
186         DbDataAdapter GetDataAdapter(IDbCommand selectCommand);
187         /// <summary>
188         /// 使用 IDbCommand 和 IDbConnection 对象初始化 DbDataAdapter 类的一个新实例。
189         /// </summary>
190         /// <param name="selectCommandText">一个 System.String,它是将要由 DbDataAdapter 的 IDbCommand 属性使用的 Transact-SQL SELECT 语句或存储过程。</param>
191         /// <param name="selectConnection">数据库链接字符串</param>
192         /// <returns></returns> 
193         DbDataAdapter GetDataAdapter(string selectCommandText, IDbConnection selectConnection);
194         //添加参数
195         IDataParameter GetParaneter(string param_name, DbType db_type);
196         IDataParameter GetParaneter(string param_name, string param_text);
197         IDataParameter GetParaneter(string param_name, DbType db_type, byte[] fs);
198         IDataParameter GetParaneter(string param_name, DbType db_type, string param_text);
199         IDataParameter GetParaneter(string param_name, DbType db_type, string param_text, int para_size);
200         IDataParameter GetParaneter(string param_name, DbType db_type, string param_text, ParameterDirection ptype);
201     }
202     /// <summary>
203     /// SqlServer数据库
204     /// author:陈彦斌
205     /// 时间:2019年7月14日23:37:25
206     /// </summary>
207     public sealed class SqlServerProvider : IDbProvider
208     {
209         private string _get_conn;
210         private const string paramhead = "@";
211         public SqlServerProvider(string strConn)
212         {
213             _get_conn = strConn;
214         }
215         public string connStr
216         {
217             get
218             {
219                 return _get_conn;
220             }
221 
222             set
223             {
224                 _get_conn = value;
225             }
226         }
227 
228         public IDbCommand GetCommand()
229         {
230             return new SqlCommand();
231         }
232 
233         public IDbCommand GetCommand(string cmdText)
234         {
235             return new SqlCommand(cmdText);
236         }
237 
238         public IDbCommand GetCommand(string cmdText, IDbConnection connection)
239         {
240             return new SqlCommand(cmdText, (SqlConnection)connection);
241         }
242 
243         public IDbCommand GetCommand(IDbConnection connection, IDbTransaction transaction)
244         {
245             return GetCommand(null, connection, transaction);
246         }
247 
248         public IDbCommand GetCommand(string cmdText, IDbConnection connection, IDbTransaction transaction)
249         {
250             return new SqlCommand(cmdText, (SqlConnection)connection, (SqlTransaction)transaction);
251         }
252 
253         public IDbConnection GetConnection()
254         {
255             return new SqlConnection(this.connStr);
256         }
257 
258         public IDbConnection GetConnection(string connectionString)
259         {
260             return new SqlConnection(connectionString);
261         }
262 
263         public DbDataAdapter GetDataAdapter()
264         {
265             return new SqlDataAdapter();
266         }
267 
268         public DbDataAdapter GetDataAdapter(IDbCommand selectCommand)
269         {
270             return new SqlDataAdapter((SqlCommand)selectCommand);
271         }
272 
273         public DbDataAdapter GetDataAdapter(string selectCommandText, IDbConnection selectConnection)
274         {
275             return new SqlDataAdapter(selectCommandText, (SqlConnection)selectConnection);
276         }
277 
278         public IDataParameter GetParaneter(string param_name, string param_text)
279         {
280             return new SqlParameter(paramhead + param_name, param_text);
281         }
282 
283         public IDataParameter GetParaneter(string param_name, DbType db_type)
284         {
285             return new SqlParameter(paramhead + param_name, db_type);
286         }
287 
288         public IDataParameter GetParaneter(string param_name, DbType db_type, string param_text)
289         {
290             SqlParameter param = new SqlParameter(paramhead + param_name, db_type);
291             param.Value = param_text;
292             return param;
293         }
294 
295         public IDataParameter GetParaneter(string param_name, DbType db_type, byte[] fs)
296         {
297             SqlParameter param = new SqlParameter(paramhead + param_name, db_type);
298             param.Value = fs;
299             return param;
300         }
301 
302         public IDataParameter GetParaneter(string param_name, DbType db_type, string param_text, ParameterDirection ptype)
303         {
304             SqlParameter param = new SqlParameter(paramhead + param_name, db_type);
305             param.Value = param_text;
306             param.Direction = ptype;
307             return param;
308         }
309 
310         public IDataParameter GetParaneter(string param_name, DbType db_type, string param_text, int para_size)
311         {
312             SqlParameter param = new SqlParameter(paramhead + param_name, db_type);
313             param.Value = param_text;
314             param.Size = para_size;
315             return param;
316         }
317     }
318     /// <summary>
319     /// Oracle数据库
320     /// author:陈彦斌
321     /// 时间:2019年7月14日23:37:50
322     /// </summary>
323     public sealed class OracleProvider : IDbProvider
324     {
325         private string _get_conn;
326         public OracleProvider(string strConn)
327         {
328             _get_conn = strConn;
329         }
330         public string connStr
331         {
332             get
333             {
334                 return _get_conn;
335             }
336 
337             set
338             {
339                 _get_conn = value;
340             }
341         }
342 
343         public IDbCommand GetCommand()
344         {
345             return new OracleCommand();
346         }
347 
348         public IDbCommand GetCommand(string cmdText)
349         {
350             return new OracleCommand(cmdText);
351         }
352 
353         public IDbCommand GetCommand(IDbConnection connection, IDbTransaction transaction)
354         {
355             return GetCommand(null, connection, transaction);
356         }
357 
358         public IDbCommand GetCommand(string cmdText, IDbConnection connection)
359         {
360             return new OracleCommand(cmdText, (OracleConnection)connection);
361         }
362 
363         public IDbCommand GetCommand(string cmdText, IDbConnection connection, IDbTransaction transaction)
364         {
365             return new OracleCommand(cmdText, (OracleConnection)connection, (OracleTransaction)transaction);
366         }
367 
368         public IDbConnection GetConnection()
369         {
370             return new OracleConnection(this.connStr);
371         }
372 
373         public IDbConnection GetConnection(string connectionString)
374         {
375             return new OracleConnection(connectionString);
376         }
377 
378         public DbDataAdapter GetDataAdapter()
379         {
380             return new OracleDataAdapter();
381         }
382 
383         public DbDataAdapter GetDataAdapter(IDbCommand selectCommand)
384         {
385             return new OracleDataAdapter((OracleCommand)selectCommand);
386         }
387 
388         public DbDataAdapter GetDataAdapter(string selectCommandText, IDbConnection selectConnection)
389         {
390             return new OracleDataAdapter(selectCommandText, (OracleConnection)selectConnection);
391         }
392 
393         public IDataParameter GetParaneter(string param_name, string param_text)
394         {
395             return new OracleParameter(param_name, param_text);
396         }
397 
398         public IDataParameter GetParaneter(string param_name, DbType db_type)
399         {
400             return new OracleParameter(param_name, db_type);
401         }
402 
403         public IDataParameter GetParaneter(string param_name, DbType db_type, string param_text)
404         {
405             OracleParameter param = new OracleParameter(param_name, db_type);
406             param.Value = param_text;
407             return param;
408         }
409 
410         public IDataParameter GetParaneter(string param_name, DbType db_type, byte[] fs)
411         {
412             OracleParameter param = new OracleParameter(param_name, db_type);
413             param.Value = fs;
414             return param;
415         }
416 
417         public IDataParameter GetParaneter(string param_name, DbType db_type, string param_text, ParameterDirection ptype)
418         {
419             OracleParameter param = new OracleParameter();
420             param.ParameterName = param_name;
421             if (db_type == DbType.Int32)
422             {
423                 param.OracleType = OracleType.Number;
424                 param.Value = Convert.ToDecimal(param_text);
425             }
426             else if (db_type == DbType.String)
427             {
428                 param.OracleType = OracleType.VarChar;
429                 param.Value = param_text;
430             }
431             else
432             {
433                 param.DbType = db_type;
434                 param.Value = param_text;
435             }
436 
437             param.Direction = ptype;
438             return param;
439         }
440 
441         public IDataParameter GetParaneter(string param_name, DbType db_type, string param_text, int para_size)
442         {
443             OracleParameter param = new OracleParameter(param_name, db_type);
444             param.Value = param_text;
445             param.Size = para_size;
446             return param;
447         }
448     }
449 }

四、数据库帮助类(DbUtil.cs)

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Data;
  4 using System.Reflection;
  5 using System.Data.Common;
  6 
  7 namespace Tool
  8 {
  9     /// <summary>
 10     /// 数据库操作类
 11     /// author:陈彦斌
 12     /// 时间:2019年7月14日23:39:07
 13     /// </summary>
 14     public sealed class DbUtil : DbBaseTool
 15     {
 16         private static object lockHelper = new object();
 17         private static SystemConfig SysCfg;
 18         private static IDbProvider defaultPro;
 19         private static string connectionString { get { return SysCfg.ConnectionString; } }
 20         public static void resetDbUtil()
 21         {
 22             lock (lockHelper)
 23             {
 24                 if (defaultPro == null)
 25                 {
 26                     try
 27                     {
 28                         SysCfg = ConfigHelper.GetAppSettingsAllInfo();
 29                         if (SysCfg.dbType.ToLower() == "sqlserver")
 30                         {
 31                             defaultPro = new SqlServerProvider(connectionString);
 32                         }
 33                         else if (SysCfg.dbType.ToLower() == "oracle")
 34                         {
 35                             defaultPro = new OracleProvider(connectionString);
 36                         }
 37                         else
 38                         {
 39                             throw new NotImplementedException();
 40                         }
 41                     }
 42                     catch (Exception ex)
 43                     {
 44                         throw ex;
 45                     }
 46                 }
 47             }
 48         }
 49         public static void resetDbUtil(string DbName)
 50         {
 51             lock (lockHelper)
 52             {
 53                 if (defaultPro == null)
 54                 {
 55                     try
 56                     {
 57                         SysCfg = ConfigHelper.GetAppSettingsAllInfo();
 58                         if (SysCfg.dbType.ToLower() == "sqlserver")
 59                         {
 60                             defaultPro = new SqlServerProvider(connectionString);
 61                         }
 62                         else if (SysCfg.dbType.ToLower() == "oracle")
 63                         {
 64                             defaultPro = new OracleProvider(connectionString);
 65                         }
 66                         else
 67                         {
 68                             throw new NotImplementedException();
 69                         }
 70                     }
 71                     catch (Exception ex)
 72                     {
 73                         throw ex;
 74                     }
 75                 }
 76             }
 77         }
 78         static DbUtil()
 79         {
 80             if (defaultPro == null)
 81             {
 82                 resetDbUtil();
 83             }
 84         }
 85         /// <summary>
 86         /// 执行查询SQL语句,返回DataTable
 87         /// </summary>
 88         /// <param name="strSql">查询SQL语句</param>
 89         /// <returns></returns>
 90         public static DataTable QueryDT(string strSql)
 91         {
 92             using (IDbConnection conn = defaultPro.GetConnection())
 93             {
 94                 if (conn.State!=ConnectionState.Open)
 95                 {
 96                     conn.Open();
 97                 }
 98                 try
 99                 {
100                     PrintErrorStrSql(strSql);
101                     IDbDataAdapter adap = defaultPro.GetDataAdapter(strSql, conn);
102                     DataTable dt = new DataTable();
103                     DataSet ds = new DataSet();
104                     adap.Fill(ds);
105                     dt = ds.Tables[0];
106                     return dt;
107                 }
108                 catch (DbException ex)
109                 {
110                     throw new Exception(ex.Message);
111                 }
112                 finally
113                 {
114                     conn.Close();
115                 }
116             }
117         }
118         /// <summary>
119         /// 执行查询SQL语句,反射会实体类
120         /// </summary>
121         /// <typeparam name="T">数据类型</typeparam>
122         /// <param name="strSql">查询SQL语句</param>
123         /// <returns></returns>
124         public static T QueryDT<T>(string strSql) where T : new()
125         {
126             try
127             {
128                 T t = new T();
129                 DataTable dt = QueryDT(strSql);
130                 foreach (DataRow dr in dt.Rows)
131                 {
132                     foreach (PropertyInfo pi in t.GetType().GetProperties())
133                     {
134                         if (dt.Columns.Contains(pi.Name))
135                         {
136                             if (!pi.CanWrite) continue;
137                             var value = dr[pi.Name];
138                             if (value != DBNull.Value)
139                             {
140                                 switch (pi.PropertyType.FullName)
141                                 {
142                                     case "System.Decimal":
143                                         pi.SetValue(t, decimal.Parse(value.ToString()), null);
144                                         break;
145                                     case "System.String":
146                                         pi.SetValue(t, value.ToString(), null);
147                                         break;
148                                     case "System.Int32":
149                                         pi.SetValue(t, int.Parse(value.ToString()), null);
150                                         break;
151                                     default:
152                                         pi.SetValue(t, value, null);
153                                         break;
154                                 }
155                             }
156                         }
157                     }
158                 }
159                 return t;
160             }
161             catch (DbException ex)
162             {
163                 throw new Exception(ex.Message);
164             }
165         }
166         /// <summary>
167         /// 执行查询SQL语句,反射出实体类集合
168         /// </summary>
169         /// <typeparam name="T">数据类型</typeparam>
170         /// <param name="strSql">查询SQL语句</param>
171         /// <returns></returns>
172         public static List<T> QueryList<T>(string strSql) where T : new()
173         {
174             try
175             {
176                 List<T> ts = new List<T>();
177                 ts=toEntity<T>(QueryDT(strSql));
178                 return ts;
179             }
180             catch (DbException ex)
181             {
182                 throw new Exception(ex.Message);
183             }
184         }
185         /// <summary>
186         /// 将DataTable转换成实体类
187         /// </summary>
188         /// <typeparam name="T">实体类</typeparam>
189         /// <param name="dt">DataTable</param>
190         /// <returns></returns>
191         public static List<T> toEntity<T>(DataTable dt) where T : new()
192         {
193             List<T> ts = new List<T>();
194             foreach (DataRow dr in dt.Rows)
195             {
196                 T t = new T();
197                 foreach (PropertyInfo pi in t.GetType().GetProperties())
198                 {
199                     if (dt.Columns.Contains(pi.Name))
200                     {
201                         if (!pi.CanWrite) continue;
202                         var value = dr[pi.Name];
203                         if (value != DBNull.Value)
204                         {
205                             switch (pi.PropertyType.FullName)
206                             {
207                                 case "System.Decimal":
208                                     pi.SetValue(t, decimal.Parse(value.ToString()), null);
209                                     break;
210                                 case "System.String":
211                                     pi.SetValue(t, value.ToString(), null);
212                                     break;
213                                 case "System.Int32":
214                                     pi.SetValue(t, int.Parse(value.ToString()), null);
215                                     break;
216                                 default:
217                                     pi.SetValue(t, value, null);
218                                     break;
219                             }
220                         }
221                     }
222                 }
223                 ts.Add(t);
224             }
225             return ts;
226         }
227         /// <summary>
228         /// 对数据进行增、删、改
229         /// </summary>
230         /// <param name="strSql">SQL语句</param>
231         /// <returns></returns>
232         public static int ExecuteSql(string strSql)
233         {
234             using (IDbConnection conn = defaultPro.GetConnection())
235             {
236                 using (IDbCommand cmd = defaultPro.GetCommand(strSql, conn))
237                 {
238                     try
239                     {
240                         if (conn.State != ConnectionState.Open)
241                         {
242                             conn.Open();
243                         }
244                         return cmd.ExecuteNonQuery();
245                     }
246                     catch (Exception ex)
247                     {
248                         conn.Close();
249                         throw ex;
250                     }
251                     finally
252                     {
253                         conn.Close();
254                     }
255                 }
256             }
257         }
258         /// <summary>
259         /// 对数据进行增、删、改
260         /// </summary>
261         /// <param name="strSql">SQL语句</param>
262         /// <returns></returns>
263         public static int ExecuteSqlTrans(string strSql)
264         {
265             using (IDbConnection conn = defaultPro.GetConnection())
266             {
267                 if (conn.State != ConnectionState.Open)
268                 {
269                     conn.Open();
270                 }
271                 IDbTransaction trans = conn.BeginTransaction();
272                 IDbCommand cmd = defaultPro.GetCommand(conn, trans);
273                 try
274                 {
275                     int resCount = 0;
276                     PrintErrorStrSql(strSql);
277                     cmd.CommandText = strSql;
278                     resCount = cmd.ExecuteNonQuery();
279                     trans.Commit();
280                     return resCount;
281                 }
282                 catch (Exception ex)
283                 {
284                     trans.Rollback();
285                     throw ex;
286                 }
287                 finally
288                 {
289                     cmd.Dispose();
290                     conn.Close();
291                 }
292             }
293         }
294         /// <summary>
295         /// 对数据进行增、删、改
296         /// </summary>
297         /// <param name="listSql">SQL集合</param>
298         /// <returns></returns>
299         public static int ExecuteSqlTrans(List<string> listSql)
300         {
301             using (IDbConnection conn = defaultPro.GetConnection())
302             {
303                 if (conn.State != ConnectionState.Open)
304                 {
305                     conn.Open();
306                 }
307                 IDbTransaction trans = conn.BeginTransaction();
308                 IDbCommand cmd = defaultPro.GetCommand(conn, trans);
309                 try
310                 {
311                     int resCount = 0;
312                     string strSql = string.Empty;
313                     for (int i = 0; i < listSql.Count; i++)
314                     {
315                         strSql = listSql[i];
316                         PrintErrorStrSql(strSql);
317                         cmd.CommandText = strSql;
318                         resCount += cmd.ExecuteNonQuery();
319                     }
320                     trans.Commit();
321                     return resCount;
322                 }
323                 catch (Exception ex)
324                 {
325                     trans.Rollback();
326                     throw ex;
327                 }
328                 finally
329                 {
330                     cmd.Dispose();
331                     conn.Close();
332                 }
333             }
334         }
335         /// <summary>
336         /// 对数据进行增、删、改
337         /// </summary>
338         /// <param name="strSql">SQL语句</param>
339         /// <param name="pms">可变参数</param>
340         /// <returns></returns>
341         public static int ExecuteSqlTrans(string strSql, IDataParameter[] pms)
342         {
343             using (IDbConnection conn = defaultPro.GetConnection())
344             {
345                 if (conn.State != ConnectionState.Open)
346                 {
347                     conn.Open();
348                 }
349                 IDbTransaction trans = conn.BeginTransaction();
350                 using (IDbCommand cmd = defaultPro.GetCommand(conn, trans))
351                 {
352                     if (pms != null)
353                     {
354                         foreach (IDataParameter item in pms)
355                         {
356                             cmd.Parameters.Add(item);
357                         }
358                     }
359                     try
360                     {
361                         int resCount = 0;
362                         PrintErrorStrSql(strSql);
363                         cmd.CommandText = strSql;
364                         resCount = cmd.ExecuteNonQuery();
365                         trans.Commit();
366                         return resCount;
367                     }
368                     catch (Exception ex)
369                     {
370                         trans.Rollback();
371                         throw ex;
372                     }
373                     finally
374                     {
375                         conn.Close();
376                     }
377                 }
378             }
379         }
380         private static void PrintErrorStrSql(string strSql)
381         {
382             if (SysCfg.IsPrint == "true" && !StringUtil.isNullOrBlank(SysCfg.PrintErrorSqlPath))
383             {
384                 PrintSqlTool.LogBasePath = SysCfg.PrintErrorSqlPath;
385                 PrintSqlTool.execSqlQueue.Enqueue(strSql);
386                 //PrintSqlTool.PrintSqlToText(SysCfg.PrintErrorSqlPath, strSql);
387             }
388         }
389     }
390 }

五、实体类基类(EntityBase.cs)

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Reflection;
  4 using System.Web;
  5 using System.Text;
  6 using Sam.OA.Common;
  7 
  8 namespace Sam.OA.Model
  9 {
 10     /// <summary>
 11     /// 实体类基类
 12     /// author:陈彦斌
 13     /// 时间:2019年7月14日23:39:07
 14     /// </summary>
 15     [Serializable]
 16     public abstract class EntityBase
 17     {
 18         /// <summary>
 19         /// 获取主键
 20         /// </summary>
 21         /// <returns></returns>
 22         public abstract string GetPrimaryKey();
 23         /// <summary>
 24         /// 获取INSERT语句
 25         /// </summary>
 26         /// <returns></returns>
 27         public string GetInsertSql()
 28         {
 29             try
 30             {
 31                 Type t = this.GetType();
 32                 string tableName = t.Name,pKey=this.GetPrimaryKey(),fields=string.Empty,values=string.Empty,temp=null;
 33                 foreach (PropertyInfo pi in t.GetProperties())
 34                 {
 35                     if (!pi.CanWrite) continue;
 36                     if (pi.Name.Equals(pKey))
 37                     {
 38                         continue;
 39                     }
 40                     temp = GetByTypeStr(pi);
 41                     fields += pi.Name + ",";
 42                     values += temp + ",";
 43                 }
 44                 return string.Format("Insert into {0}({1}) Values({2})", tableName, fields.TrimEnd(‘,‘), values.TrimEnd(‘,‘));
 45             }
 46             catch
 47             {
 48                 throw;
 49             }
 50         }
 51         /// <summary>
 52         /// 通过POST/GET请求获取Insert语句
 53         /// </summary>
 54         /// <param name="arrPostOrGetAllKey">POST/GET请求的所有键</param>
 55         /// <param name="HttpRequest"></param>
 56         /// <returns></returns>
 57         public string GetInsertSql(string[] arrPostOrGetAllKey, HttpRequest Request)
 58         {
 59             try
 60             {
 61 
 62                 Dictionary<string, string> dd = new Dictionary<string, string>();
 63                 string key = string.Empty;
 64                 string value = string.Empty;
 65                 for (int i = 0; i < arrPostOrGetAllKey.Length; i++)
 66                 {
 67                     key = Request.Form.AllKeys[i];
 68                     value = Request.Form[key];
 69                     if (StringUtil.isNullOrBlank(key))
 70                     {
 71                         key = Request.QueryString.AllKeys[i];
 72                         value = Request.QueryString[key];
 73                     }
 74                     dd.Add(key, value);
 75                 }
 76                 Type t = this.GetType();
 77                 PropertyInfo[] pInfos = t.GetProperties();
 78                 string tableName = t.Name, pKey = this.GetPrimaryKey(), pValue = string.Empty, str_fields = string.Empty;
 79                 StringBuilder s_fields = new StringBuilder();
 80                 StringBuilder s_values = new StringBuilder();
 81                 int keyIndex = -1;
 82                 for (int i = 0; i < pInfos.Length; i++)
 83                 {
 84                     if (pInfos[i].Name.Equals(pKey))
 85                     {
 86                         keyIndex = i;
 87                         if (dd.ContainsKey(pKey))
 88                         {
 89                             pValue = dd[pKey];
 90                         }
 91                         continue;
 92                     }
 93                     if (dd.ContainsKey(pInfos[i].Name))
 94                     {
 95                         s_fields.Append(pInfos[i].Name).Append(",");
 96                         s_values.Append(GetByTypeStr(dd[pInfos[i].Name])).Append(",");
 97                     }
 98                 }
 99                 return string.Format("INSERT INTO {0} ({1}) VALUES ({2})", tableName, s_fields.ToString().TrimEnd(‘,‘), s_values.ToString().TrimEnd(‘,‘));
100             }
101             catch
102             {
103                 throw;
104             }
105         }
106         /// <summary>
107         /// 根据主键获取删除条件
108         /// </summary>
109         /// <typeparam name="T"></typeparam>
110         /// <param name="pKey"></param>
111         /// <returns></returns>
112         public string GetDeleteSql<T>(int pKey)
113         {
114             try
115             {
116                 Type t = this.GetType();
117                 string table = t.Name;
118                 return string.Format("DELETE FROM {0} WHERE {1} = {2}", table, this.GetPrimaryKey(), pKey);
119             }
120             catch
121             {
122                 throw;
123             }
124         }
125         /// <summary>
126         /// 根据主键获取删除条件
127         /// </summary>
128         /// <param name="pKey"></param>
129         /// <returns></returns>
130         public string GetDeleteSql(int pKey)
131         {
132             try
133             {
134                 Type t = this.GetType();
135                 string table = t.Name;
136                 return string.Format("DELETE FROM {0} WHERE {1} = {2}", table, this.GetPrimaryKey(), pKey);
137             }
138             catch
139             {
140                 throw;
141             }
142         }
143         /// <summary>
144         /// 根据条件获取删除语句eg:name=‘alex‘ and age=8
145         /// </summary>
146         /// <typeparam name="T"></typeparam>
147         /// <param name="deleteWhere">删除条件eg:name=‘alex‘ and age=8</param>
148         /// <returns></returns>
149         public string GetDeleteSql<T>(string deleteWhere)
150         {
151             try
152             {
153                 Type t = this.GetType();
154                 string table = t.Name;
155                 return string.Format("DELETE FROM {0} WHERE {1}", table, deleteWhere);
156             }
157             catch
158             {
159                 throw;
160             }
161         }
162         /// <summary>
163         /// 根据条件获取删除语句eg:name=‘alex‘ and age=8
164         /// </summary>
165         /// <typeparam name="T"></typeparam>
166         /// <param name="deleteWhere">删除条件eg:name=‘alex‘ and age=8</param>
167         /// <returns></returns>
168         public string GetDeleteSql(string deleteWhere)
169         {
170             try
171             {
172                 Type t = this.GetType();
173                 string table = t.Name;
174                 return string.Format("DELETE FROM {0} WHERE {1}", table, deleteWhere);
175             }
176             catch
177             {
178                 throw;
179             }
180         }
181         /// <summary>
182         /// 获取UPDATE语句
183         /// </summary>
184         /// <returns></returns>
185         public string GetUpdateSql()
186         {
187             try
188             {
189                 Type t = this.GetType();
190                 PropertyInfo[] pInfos = t.GetProperties();
191                 string tableName = t.Name, pKey = this.GetPrimaryKey(), str_fields=string.Empty;
192                 int keyIndex = -1;
193                 for (int i = 0; i < pInfos.Length; i++)
194                 {
195                     if (pInfos[i].Name.Equals(pKey))
196                     {
197                         keyIndex = i;
198                         continue;
199                     }
200                     str_fields += pInfos[i].Name + " = " + GetByTypeStr(pInfos[i]) + ",";
201                 }
202                 return string.Format("UPDATE {0} SET {1} WHERE {2} = {3}", tableName, str_fields.TrimEnd(‘,‘), pKey, GetByTypeStr(pInfos[keyIndex]));
203             }
204             catch
205             {
206                 throw;
207             }
208         }
209         /// <summary>
210         /// 通过POST/GET请求获取UPDATE语句
211         /// </summary>
212         /// <param name="arrPostOrGetAllKey">POST/GET请求的所有键</param>
213         /// <param name="HttpRequest"></param>
214         /// <returns></returns>
215         public string GetUpdateSql(string[] arrPostOrGetAllKey, HttpRequest Request)
216         {
217             try
218             {
219 
220                 Dictionary<string, string> dd = new Dictionary<string, string>();
221                 string key = string.Empty;
222                 string value = string.Empty;
223                 for (int i = 0; i < arrPostOrGetAllKey.Length; i++)
224                 {
225                     key = Request.Form.AllKeys[i];
226                     value = Request.Form[key];
227                     if (StringUtil.isNullOrBlank(key))
228                     {
229                         key = Request.QueryString.AllKeys[i];
230                         value = Request.QueryString[key];
231                     }
232                     dd.Add(key, value);
233                 }
234                 Type t = this.GetType();
235                 PropertyInfo[] pInfos = t.GetProperties();
236                 string tableName = t.Name, pKey = this.GetPrimaryKey(), pValue = string.Empty, str_fields = string.Empty;
237                 int keyIndex = -1;
238                 for (int i = 0; i < pInfos.Length; i++)
239                 {
240                     if (pInfos[i].Name.Equals(pKey))
241                     {
242                         keyIndex = i;
243                         if (dd.ContainsKey(pKey))
244                         {
245                             pValue = dd[pKey];
246                         }
247                         continue;
248                     }
249                     if (dd.ContainsKey(pInfos[i].Name))
250                     {
251                         str_fields += pInfos[i].Name + " = " + GetByTypeStr(dd[pInfos[i].Name]) + ",";
252                     }
253                 }
254                 if (StringUtil.isNullOrBlank(pValue))
255                 {
256                     throw new Exception("更新条件不能为空!");
257                 }
258                 return string.Format("UPDATE {0} SET {1} WHERE {2} = {3}", tableName, str_fields.TrimEnd(‘,‘), pKey, GetByTypeStr(pValue));
259             }
260             catch
261             {
262                 throw;
263             }
264         }
265         /// <summary>
266         /// 根据实体类组装查询条件,并返回查询语句
267         /// </summary>
268         /// <typeparam name="T">数据类型</typeparam>
269         /// <param name="t">实体类实例</param>
270         /// <returns></returns>
271         public string GetSelectSql<T>(T t) where T:class
272         {
273             try
274             {
275                 Type t1 = t.GetType();
276                 string tableName = t1.Name, temp = null;
277                 StringBuilder sb = new StringBuilder();
278                 foreach (PropertyInfo pi in t1.GetProperties())
279                 {
280                     if (!pi.CanWrite) continue;
281                     temp = GetByTypeStr(pi);
282                     if (!StringUtil.isNullOrBlank(temp)&& temp!="0")
283                     {
284                         sb.Append(" AND ").Append(pi.Name).Append(" = ").Append(temp).Append(" AND ");
285                     }
286                 }
287                 if (sb.ToString().Length > 0)
288                 {
289                     string query_sql = "SELECT * FROM {0} WHERE 1=1 {1}";
290                     return string.Format(query_sql, tableName,sb.ToString().Substring(0,sb.ToString().Length-4));
291                 }
292                 return "";
293             }
294             catch (Exception ex)
295             {
296                 throw ex;
297             }
298         }
299         /// <summary>
300         /// 根据查询条件,返回查询语句eg:a=‘123‘ and b=‘456‘
301         /// </summary>
302         /// <typeparam name="T">数据类型</typeparam>
303         /// <param name="strWhere">WHERE条件:eg: a=‘123‘ and b=‘456‘ .....</param>
304         /// <returns></returns>
305         public string GetSelectSql<T>(string strWhere) where T : class
306         {
307             if (!StringUtil.isNullOrBlank(strWhere))
308             {
309                 Type t = this.GetType();
310                 string tableName = t.Name;
311                 return string.Format("SELECT * FROM {0} WHERE 1=1 AND ",tableName, strWhere);
312             }
313             return "";
314         }
315         /// <summary>
316         /// 根据查询条件,返回查询语句eg:a=‘123‘ and b=‘456‘
317         /// </summary>
318         /// <param name="strWhere">WHERE条件:eg: a=‘123‘ and b=‘456‘ .....</param>
319         /// <returns></returns>
320         public string GetSelectSql(string strWhere)
321         {
322             if (!StringUtil.isNullOrBlank(strWhere))
323             {
324                 Type t = this.GetType();
325                 string tableName = t.Name;
326                 return string.Format("SELECT * FROM {0} WHERE 1=1 AND ", tableName, strWhere);
327             }
328             return "";
329         }
330         /// <summary>
331         /// 获取表中所有数据
332         /// </summary>
333         /// <typeparam name="T">数据类型</typeparam>
334         /// <returns></returns>
335         public string GetSelectSql<T>() where T : class
336         {
337             try
338             {
339                 return string.Format("SELECT * FROM {0}", this.GetType().Name);
340             }
341             catch (Exception ex)
342             {
343                 throw ex;
344             }            
345         }
346         /// <summary>
347         /// 获取表中所有数据
348         /// </summary>
349         /// <returns></returns>
350         public string GetSelectSql()
351         {
352             try
353             {
354                 return string.Format("SELECT * FROM {0}", this.GetType().Name);
355             }
356             catch (Exception ex)
357             {
358                 throw ex;
359             }            
360         }
361         /// <summary>
362         /// 根据主键查询表
363         /// </summary>
364         /// <typeparam name="T"></typeparam>
365         /// <param name="pKey"></param>
366         /// <returns></returns>
367         public string SelectByPrimaryKey<T>(int pKey)
368         {
369             try
370             {
371                 Type t = this.GetType();
372                 string table = t.Name;
373                 return string.Format("SELECT * FROM {0} WHERE {1} = {2}", table, this.GetPrimaryKey(), pKey);
374             }
375             catch
376             {
377                 throw;
378             }
379         }
380         /// <summary>
381         /// 根据主键查询表
382         /// </summary>
383         /// <typeparam name="T"></typeparam>
384         /// <param name="pKey"></param>
385         /// <returns></returns>
386         public string SelectByPrimaryKey(int pKey)
387         {
388             try
389             {
390                 Type t = this.GetType();
391                 string table = t.Name;
392                 return string.Format("SELECT * FROM {0} WHERE {1} = {2}", table, this.GetPrimaryKey(), pKey);
393             }
394             catch
395             {
396                 throw;
397             }
398         }
399         /// <summary>
400         /// 获取表中总行数
401         /// </summary>
402         /// <typeparam name="T">数据类型</typeparam>
403         /// <returns></returns>
404         public string GetAllRowsCount<T>() where T:class
405         {
406             return string.Format("SELECT COUNT(*) FROM {0}",this.GetType().Name);
407         }
408         /// <summary>
409         /// 获取表中总行数
410         /// </summary>
411         /// <returns></returns>
412         public string GetAllRowsCount()
413         {
414             try
415             {
416                 Type t = this.GetType();
417                 string table = t.Name;
418                 return string.Format("SELECT COUNT(*) FROM {0}", table);
419             }
420             catch
421             {
422                 throw;
423             }
424         }
425         /// <summary>
426         /// 获取分页数据
427         /// </summary>
428         /// <param name="pageSize">一页多少条数据</param>
429         /// <param name="pageIndex">当前页的索引</param>
430         /// <returns></returns>
431         public virtual string GetPageData(int pageSize,int pageIndex)
432         {
433             try
434             {
435                 int first = pageSize * (pageIndex - 1)+1;
436                 int last = pageSize * pageIndex;
437                 Type t = this.GetType();
438                 return string.Format(@"SELECT * FROM (SELECT ROW_NUMBER() over (order by {0}) as row,TT.* from {1} TT) TTT
439 WHERE TTT.row BETWEEN {2} AND {3}",this.GetPrimaryKey(), t.Name, first,last);
440             }
441             catch
442             {
443                 throw;
444             }
445         }
446         /// <summary>
447         /// 获取分页数据
448         /// </summary>
449         /// <param name="pageSize">一页多少条数据</param>
450         /// <param name="pageIndex">当前页的索引</param>
451         /// <param name="objOrderBy">排序规则</param>
452         /// <returns></returns>
453         public virtual string GetPageData(int pageSize, int pageIndex, object objOrderBy)
454         {
455             try
456             {
457                 int first = pageSize * (pageIndex - 1) + 1;
458                 int last = pageSize * pageIndex;
459                 Type t = this.GetType();
460                 return string.Format(@"SELECT * FROM (SELECT ROW_NUMBER() over (order by {0}) as row,TT.* from {1} TT) TTT
461 WHERE TTT.row BETWEEN {2} AND {3}", objOrderBy.ToString(), t.Name, first, last);
462             }
463             catch
464             {
465                 throw;
466             }
467         }
468         /// <summary>
469         /// 根据数据类型反射字段值
470         /// </summary>
471         /// <param name="pInfo">公共属性</param>
472         /// <returns></returns>
473         private string GetByTypeStr(PropertyInfo pInfo)
474         {
475             try
476             {
477                 string result_str = string.Empty;
478                 Type t = pInfo.PropertyType;
479                 object obj = pInfo.GetValue(this, null);
480                 bool valueNull = StringUtil.isNullOrBlank(obj);
481                 if (t == typeof(string))
482                 {
483                     result_str = valueNull ? "null" : "‘" + obj.ToString().Replace("--","") + "‘";
484                 }
485                 else if (t == typeof(System.Decimal) || t == typeof(System.Int16) || t == typeof(System.Int32) || t == typeof(System.Int64))
486                 {
487                     result_str = t.Name == "Nullable`1"&& valueNull ? "null" : obj.ToString();                 
488                 }
489                 else if(t==typeof(DateTime)||t.Name== "Nullable`1")
490                 {
491                     if (valueNull||DateTime.MinValue.Equals(obj)|| t.Name == "Nullable`1")
492                     {
493                         result_str = "null";
494                     }
495                     else
496                     {
497                         result_str = "‘"+obj.ToString().Replace("年", "-").Replace("月", "-").Replace("日", "")+"‘";
498                     }
499                 }
500                 return result_str;
501             }
502             catch
503             {
504                 throw;
505             }
506         }
507         /// <summary>
508         /// 获取字段值
509         /// </summary>
510         /// <param name="value">值</param>
511         /// <returns></returns>
512         private string GetByTypeStr(object obj)
513         {
514             try
515             {
516                 if (StringUtil.IsDate(obj))
517                 {
518                                

热门排行

今日推荐

热门手游