热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

闲暇时间自己写的DB类,支持MDB,SQLITE,SQLSERVER,支持查询、事务,对象直接插入和更新操作等!(10.2更新)

第一次把自己的东西推送到首页!大侠们请勿见笑啊!一直做数据库,最近花了点时间把自己常用的东西封装在一起。感觉比以前方便了很多!特此拿出来分享下,如有不足指出,欢迎指出纠正和完善!D

第一次把自己的东西推送到首页!大侠们请勿见笑啊!

一直做数据库,最近花了点时间把自己常用的东西封装在一起。感觉比以前方便了很多!特此拿出来分享下,如有不足指出,欢迎指出纠正和完善!

DBHelper
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Text;
  4 using System.Data;
  5 using System.Data.Common;
  6 using System.Reflection;
  7 
  8 namespace DBHelper
  9 {
 10     public sealed class DB : IDisposable
 11     {
 12         #region 数据库类型枚举
 13         /// 
 14         /// 数据库类型
 15         /// 
 16         public enum DBType
 17         {
 18             SQLSERVER,
 19             MDB,
 20             SQLITE
 21         }
 22         #endregion
 23 
 24         #region 公共成员
 25         public string ConnectionString { get; set; } //连接字符串
 26 
 27         DBType _DbType;
 28 
 29         public DBType DbType
 30         {
 31             get { return this._DbType; }
 32             set
 33             {
 34                 this._DbType = value;
 35                 switch (value)
 36                 {
 37                     case DBType.SQLSERVER:
 38                         Factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
 39                         break;
 40                     case DBType.MDB:
 41                         Factory = DbProviderFactories.GetFactory("System.Data.OleDb");
 42                         break;
 43                     case DBType.SQLITE:
 44                         Factory = DbProviderFactories.GetFactory("System.Data.SQLite");
 45                         break;
 46                 }
 47             }
 48         } //数据库类型
 49 
 50         public string CommandText { get; set; } //查询语句
 51 
 52         //public DbParameterCollection Parameters { get; set; } //参数集合
 53 
 54 
 55 
 56         #endregion
 57 
 58         #region 私有成员
 59 
 60         private DbParameterCollection Parameters { get; set; } //参数集合
 61 
 62         #endregion
 63 
 64         #region 初始成员
 65 
 66         private DbConnection COnn= null; //连接对象
 67 
 68         private DbProviderFactory Factory = null; //数据库工厂                
 69 
 70         private List TranList = new List(); //事务集合
 71 
 72         #endregion
 73 
 74         #region 构造函数
 75         public DB()
 76         { }
 77 
 78         public DB(DBType dbType, string connectionString)
 79         {
 80             this.DbType = dbType;
 81             this.COnnectionString= connectionString;
 82             this.Parameters = Factory.CreateCommand().Parameters;
 83         }
 84         #endregion
 85 
 86         #region 初始化与自动释放
 87 
 88         public void Open()
 89         {
 90             try
 91             {
 92                 if (COnn== null)
 93                 {
 94                     COnn= Factory.CreateConnection();
 95                     Conn.COnnectionString= this.ConnectionString;
 96                     Conn.Open();
 97                 }
 98                 else
 99                 {
100                     if (Conn.State == ConnectionState.Closed)
101                         Conn.Open();
102                 }
103             }
104             catch (Exception)
105             {
106                 throw;
107             }
108         }
109 
110         public void Close()
111         {
112             try
113             {
114                 if (Conn.State == ConnectionState.Open)
115                     Conn.Close();
116             }
117             catch (Exception)
118             {
119                 throw;
120             }
121         }
122 
123         public void Dispose()
124         {
125             try
126             {
127                 if (Conn.State == ConnectionState.Open)
128                     Conn.Close();
129             }
130             catch (Exception)
131             {
132                 throw;
133             }
134         }
135         #endregion
136 
137         #region 添加查询参数
138         public void AddParameter(string name, object value)
139         {
140             var pa = Factory.CreateParameter();
141             pa.ParameterName = name;
142             pa.Value = value;
143             this.Parameters.Add(pa);
144         }
145 
146         public void AddParameters(T model) where T : class,new()
147         {
148             Type t = typeof(T);
149             Array.ForEach(t.GetProperties(), p =>
150             {
151                 AddParameter("@" + p.Name, p.GetValue(model, null));
152             });
153         }
154 
155         public void AddParameters(string[] names, object[] values)
156         {
157             if (names.Length != values.Length)
158                 throw new Exception("参数名称跟参数值数量不匹配!");
159             for (var i = 0; i )
160             {
161                 var pa = Factory.CreateParameter();
162                 pa.ParameterName = names[i];
163                 pa.Value = values[i];
164                 this.Parameters.Add(pa);
165             }
166         }
167         #endregion
168 
169         #region 创建查询参数
170         public DbParameter CreateParameter(string name, object value)
171         {
172             var pa = Factory.CreateParameter();
173             pa.ParameterName = name;
174             pa.Value = value;
175             return pa;
176         }
177 
178         public List CreateParameters(string[] names, object[] values)
179         {
180             if (names.Length != values.Length)
181                 throw new Exception("参数名称跟参数值数量不匹配!");
182             var parameters = new List();
183             for (var i = 0; i )
184             {
185                 parameters.Add(CreateParameter(names[i],values[i]));
186             }
187             return parameters;
188         }
189 
190         public List CreateParameters(T model) where T : class,new()
191         {
192             var parameters = new List();
193             Type t = typeof(T);
194             Array.ForEach(t.GetProperties(), p =>
195             {                
196                 parameters.Add(CreateParameter(p.Name, p.GetValue(model, null)));
197             });
198             return parameters;
199         }
200         #endregion
201 
202         #region 清除查询字符串和查询参数
203         /// 
204         /// 清除查询字符串和查询参数
205         /// 
206         void Clear()
207         {
208             this.CommandText = "";
209             if (this.Parameters != null)
210                 this.Parameters.Clear();
211         }
212         #endregion
213 
214         #region 返回一个DataTable
215         /// 
216         /// 返回一个DataTable
217         /// 
218         public DataTable ExecuteDataTable()
219         {
220             try
221             {
222                 using (DbCommand cmd = Factory.CreateCommand())
223                 {
224                     Open();
225                     cmd.COnnection= this.Conn;
226                     cmd.CommandText = this.CommandText;
227                     //cmd.Parameters.AddRange(this.Parameters);   
228                     if (this.Parameters != null)
229                         foreach (var para in this.Parameters)
230                         {
231                             var p = cmd.CreateParameter();
232                             p.ParameterName = (para as DbParameter).ParameterName;
233                             p.Value = (para as DbParameter).Value;
234                             cmd.Parameters.Add(p);
235                         }
236                     Clear();
237 
238                     DbDataReader dr = cmd.ExecuteReader();
239                     DataTable dt = new DataTable();
240                     dt.Load(dr);
241                     return dt;
242                 }
243             }
244             catch (Exception)
245             {
246                 throw;
247             }
248             finally
249             {
250                 Clear();
251             }
252         }
253         #endregion
254 
255         #region 执行一条更新语句
256         /// 
257         /// 执行一条更新语句
258         ///         
259         public int ExecuteNonQuery()
260         {
261             try
262             {
263                 using (DbCommand cmd = Factory.CreateCommand())
264                 {
265                     Open();
266                     cmd.COnnection= this.Conn;
267                     cmd.CommandText = this.CommandText;
268                     if (this.Parameters != null)
269                         foreach (var para in this.Parameters)
270                         {
271                             var p = cmd.CreateParameter();
272                             p.ParameterName = (para as DbParameter).ParameterName;
273                             p.Value = (para as DbParameter).Value;
274                             cmd.Parameters.Add(p);
275                         }
276                     Clear();
277                     if (this.Conn.State == ConnectionState.Closed)
278                         Open();
279                     return cmd.ExecuteNonQuery();
280                 }
281             }
282             catch (Exception)
283             {
284                 throw;
285             }
286             finally
287             {
288                 Clear();
289             }
290         }
291         #endregion
292 
293         #region 返回首行首列
294         public object ExecuteScalar()
295         {
296             try
297             {
298                 using (var cmd = Factory.CreateCommand())
299                 {
300                     Open();
301                     cmd.COnnection= this.Conn;
302                     cmd.CommandText = this.CommandText;
303                     if (this.Parameters != null)
304                         foreach (var para in this.Parameters)
305                         {
306                             var p = cmd.CreateParameter();
307                             p.ParameterName = (para as DbParameter).ParameterName;
308                             p.Value = (para as DbParameter).Value;
309                             cmd.Parameters.Add(p);
310                         }
311                     Clear();
312                     if (this.Conn.State == ConnectionState.Closed)
313                         Open();
314                     return cmd.ExecuteScalar();
315                 }
316             }
317             catch (Exception)
318             {
319                 throw;
320             }
321             finally
322             {
323                 Clear();
324             }
325         }
326         #endregion
327 
328         #region 自定义事务类
329         class myTran
330         {
331             public string queryString { get; set; }
332             public List parameters { get; set; }
333 
334             public myTran(string queryString, List parameters)
335             {
336                 this.queryString = queryString;
337                 this.parameters = parameters;
338             }
339         }
340         #endregion
341 
342         #region 添加事务
343         public void AddTran(string queryString, List parameters)
344         {
345             var tran = new myTran(queryString, parameters);
346             TranList.Add(tran);
347         }
348 
349         public void AddTran(string queryString, DbParameter parameter)
350         {
351             List paras = new List();
352             if (parameter != null)
353                 paras.Add(parameter);
354             var tran = new myTran(queryString, paras);
355             TranList.Add(tran);
356         }
357         #endregion
358 
359         #region 清除事务
360         void ClearTran()
361         {
362             TranList.Clear();
363         }
364         #endregion
365 
366         #region 执行事务
367         public void ExecuteTran()
368         {
369             try
370             {
371                 using (DbTransaction tran = Conn.BeginTransaction())
372                 {
373                     try
374                     {
375                         if (this.Conn.State == ConnectionState.Closed)
376                             Open();
377                         TranList.ForEach(m =>
378                         {
379                             using (var cmd = this.Factory.CreateCommand())
380                             {
381                                 cmd.COnnection= this.Conn;
382                                 cmd.CommandText = m.queryString;
383                                 cmd.Transaction = tran;
384                                 m.parameters.ForEach(n =>
385                                 {
386                                     cmd.Parameters.Add(n);
387                                 });
388                                 cmd.ExecuteNonQuery();
389                             }
390                         });
391                         tran.Commit();
392                     }
393                     catch (Exception)
394                     {
395                         tran.Rollback();
396                         throw;
397                     }
398                     finally
399                     {
400                         ClearTran();
401                     }
402                 }
403             }
404             catch (Exception)
405             {
406                 throw;
407             }
408             finally
409             {
410                 ClearTran();
411             }
412         }
413         #endregion
414 
415         #region 根据对象生成更新语句
416         /// 
417         /// 获取更新语句
418         /// 
419         /// 
420         /// 
421         /// 
422         /// 
423         /// 
424         public string GetUpdateString(string TableName, string IndexFieldName) where TResult : class,new()
425         {
426             string rt = "update " + TableName + " set";
427             Type t = typeof(TResult);
428             Array.ForEach(t.GetProperties(), p =>
429             {
430                 if (p.Name != IndexFieldName) rt += " " + p.Name + " = @" + p.Name + " ,";
431             });
432             rt = rt.Substring(0, rt.Length - 2);
433             if (IndexFieldName != null)
434                 rt += " where " + IndexFieldName + " = @" + IndexFieldName;
435             return rt;
436         }
437         #endregion
438 
439         #region 根据对象生成插入语句
440         /// 
441         /// 获取插入语句
442         /// 
443         /// 
444         /// 
445         /// 
446         /// 
447         /// 
448         public string GetInsertString(string TableName, string IndexFieldName) where TResult : class,new()
449         {
450             string rt = "insert into " + TableName + " (";
451             Type t = typeof(TResult);
452             Array.ForEach(t.GetProperties(), p =>
453             {
454                 if (p.Name != IndexFieldName) rt += p.Name + " , ";
455             });
456             rt = rt.Substring(0, rt.Length - 3);
457             rt += ") values (";
458             Array.ForEach(t.GetProperties(), p =>
459             {
460                 if (p.Name != IndexFieldName)
461                     rt += "@" + p.Name + " , ";
462             });
463             rt = rt.Substring(0, rt.Length - 3);
464             rt += ")";
465             return rt;
466         }
467         #endregion
468 
469         #region 对象操作
470         /// 
471         /// 将对象插入到数据库
472         /// 
473         /// 对象类型
474         /// 对象
475         /// 表名
476         /// 主键ID
477         /// 
478         public bool InsertModel(T model, string TableName, string IndexFieldName) where T : class,new()
479         {
480             this.CommandText = GetInsertString(TableName, IndexFieldName);
481             this.AddParameters(model);
482             return this.ExecuteNonQuery() > 0;
483         }
484 
485         /// 
486         /// 将对象更新到数据库
487         /// 
488         /// 对象类型
489         /// 对象
490         /// 表名
491         /// 主键ID
492         /// 
493         public bool UpdateModel(T model, string TableName, string IndexFieldName) where T : class,new()
494         {
495             this.CommandText = GetUpdateString(TableName, IndexFieldName);
496             this.AddParameters(model);
497             return this.ExecuteNonQuery() > 0;
498         }
499         #endregion
500 
501         #region 数据库静态方法
502 
503         #region 生成查询字符串
504         /// 
505         /// 返回SQLSERVER连接字符串
506         /// 
507         /// 服务器IP
508         /// 用户名
509         /// 密码
510         /// 库名
511         /// 超时时间
512         /// 
513         public static string GetSQLConnectionString(string serverIp, string uid, string pwd, string catalog, int timeout)
514         {
515             return string.Format("Server={0};User ID={1};PWD={2};Initial Catalog={3};Connect TimeOut={4};", serverIp, uid, pwd, catalog, timeout.ToString());
516         }
517 
518         /// 
519         /// 返回Mdb连接字符串
520         /// 
521         /// 数据库路径
522         /// 数据库密码
523         /// 
524         public static string GetMdbConnectionString(string filePath, string password)
525         {
526             return string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Persist Security Info=False;Jet OLEDB:Database Password={1}", filePath, password);
527         }
528 
529         /// 
530         /// 返回SQLite连接字符串
531         /// 
532         /// 数据库路径
533         /// 
534         public static string GetSQLiteConnectionString(string filePath)
535         {
536             return string.Format("Data Source={0}", filePath);
537         }
538         #endregion
539 
540         #endregion
541     }
542 }

 

使用例1:

View Code
 1 /// 
 2         /// 添加内容
 3         /// 
 4         /// 
 5         /// 
 6         public bool Insert(Model.ContentTable model)
 7         {
 8             using (var db = Program.GetDB())
 9             {
10                 try
11                 {
12                     return db.InsertModel(model, "ContentTable", "ID");
13                 }
14                 catch (Exception)
15                 {
16                     throw;
17                 }
18             }
19         }

 

使用例2:

View Code
 1 /// 
 2         /// 修改内容
 3         /// 
 4         /// 
 5         /// 
 6         public bool Update(Model.ContentTable model)
 7         {
 8             using (var db = Program.GetDB())
 9             {
10                 try
11                 {
12                     return db.UpdateModel(model, "ContentTable", "ID");
13                 }
14                 catch (Exception)
15                 {
16                     throw;
17                 }
18             }
19         }

 

使用例3:

View Code
 1 /// 
 2         /// 批量插入数据
 3         /// 
 4         /// 
 5         public void InsertAll(List lst)
 6         {
 7             using (var db = Program.GetDB())
 8             {
 9                 try
10                 {
11                     foreach(var model in lst)
12                     {
13                         var names = new string[] { 
14                             "Title",
15                             "Content"
16                         };
17                         var values = new object[]{
18                             model.Title,
19                             model.Content
20                         };
21                         db.AddTran(DB.GetInsertString("ContentTable", "ID"), db.CreateParameters(names, values));
22                     }
23                     db.ExecuteTran();
24                 }
25                 catch (Exception)
26                 {   
27                     throw;
28                 }
29             }
30         }

 

这里放上编译好的Dll文件供大家调用!点击下载


推荐阅读
  • 本文介绍了Oracle数据库中tnsnames.ora文件的作用和配置方法。tnsnames.ora文件在数据库启动过程中会被读取,用于解析LOCAL_LISTENER,并且与侦听无关。文章还提供了配置LOCAL_LISTENER和1522端口的示例,并展示了listener.ora文件的内容。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 本文介绍了一个在线急等问题解决方法,即如何统计数据库中某个字段下的所有数据,并将结果显示在文本框里。作者提到了自己是一个菜鸟,希望能够得到帮助。作者使用的是ACCESS数据库,并且给出了一个例子,希望得到的结果是560。作者还提到自己已经尝试了使用"select sum(字段2) from 表名"的语句,得到的结果是650,但不知道如何得到560。希望能够得到解决方案。 ... [详细]
  • 利用Visual Basic开发SAP接口程序初探的方法与原理
    本文介绍了利用Visual Basic开发SAP接口程序的方法与原理,以及SAP R/3系统的特点和二次开发平台ABAP的使用。通过程序接口自动读取SAP R/3的数据表或视图,在外部进行处理和利用水晶报表等工具生成符合中国人习惯的报表样式。具体介绍了RFC调用的原理和模型,并强调本文主要不讨论SAP R/3函数的开发,而是针对使用SAP的公司的非ABAP开发人员提供了初步的接口程序开发指导。 ... [详细]
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • 本文介绍了如何使用C#制作Java+Mysql+Tomcat环境安装程序,实现一键式安装。通过将JDK、Mysql、Tomcat三者制作成一个安装包,解决了客户在安装软件时的复杂配置和繁琐问题,便于管理软件版本和系统集成。具体步骤包括配置JDK环境变量和安装Mysql服务,其中使用了MySQL Server 5.5社区版和my.ini文件。安装方法为通过命令行将目录转到mysql的bin目录下,执行mysqld --install MySQL5命令。 ... [详细]
  • 本文讨论了在使用sp_msforeachdb执行动态SQL命令时,当发生错误时如何捕获数据库名称。提供了两种解决方案,并介绍了如何正确使用'?'来显示数据库名称。 ... [详细]
  • 如何查询zone下的表的信息
    本文介绍了如何通过TcaplusDB知识库查询zone下的表的信息。包括请求地址、GET请求参数说明、返回参数说明等内容。通过curl方法发起请求,并提供了请求示例。 ... [详细]
  • 解决.net项目中未注册“microsoft.ACE.oledb.12.0”提供程序的方法
    在开发.net项目中,通过microsoft.ACE.oledb读取excel文件信息时,报错“未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序”。本文提供了解决这个问题的方法,包括错误描述和代码示例。通过注册提供程序和修改连接字符串,可以成功读取excel文件信息。 ... [详细]
  • 本文介绍了一种轻巧方便的工具——集算器,通过使用集算器可以将文本日志变成结构化数据,然后可以使用SQL式查询。集算器利用集算语言的优点,将日志内容结构化为数据表结构,SPL支持直接对结构化的文件进行SQL查询,不再需要安装配置第三方数据库软件。本文还详细介绍了具体的实施过程。 ... [详细]
  • 本文介绍了Windows Vista操作系统中的用户账户保护功能,该功能是为了增强系统的安全性而设计的。通过对Vista测试版的体验,可以看到系统在安全性方面的进步。该功能的引入,为用户的账户安全提供了更好的保障。 ... [详细]
  • 使用C++编写程序实现增加或删除桌面的右键列表项
    本文介绍了使用C++编写程序实现增加或删除桌面的右键列表项的方法。首先通过操作注册表来实现增加或删除右键列表项的目的,然后使用管理注册表的函数来编写程序。文章详细介绍了使用的五种函数:RegCreateKey、RegSetValueEx、RegOpenKeyEx、RegDeleteKey和RegCloseKey,并给出了增加一项的函数写法。通过本文的方法,可以方便地自定义桌面的右键列表项。 ... [详细]
  • 本文总结和分析了JDK核心源码(2)中lang包下的基础知识,包括常用的对象类型包和异常类型包。在对象类型包中,介绍了Object类、String类、StringBuilder类、StringBuffer类和基本元素的包装类。在异常类型包中,介绍了Throwable类、Error类型和Exception类型。这些基础知识对于理解和使用JDK核心源码具有重要意义。 ... [详细]
  • MySQL语句大全:创建、授权、查询、修改等【MySQL】的使用方法详解
    本文详细介绍了MySQL语句的使用方法,包括创建用户、授权、查询、修改等操作。通过连接MySQL数据库,可以使用命令创建用户,并指定该用户在哪个主机上可以登录。同时,还可以设置用户的登录密码。通过本文,您可以全面了解MySQL语句的使用方法。 ... [详细]
  • Postgresql备份和恢复的方法及命令行操作步骤
    本文介绍了使用Postgresql进行备份和恢复的方法及命令行操作步骤。通过使用pg_dump命令进行备份,pg_restore命令进行恢复,并设置-h localhost选项,可以完成数据的备份和恢复操作。此外,本文还提供了参考链接以获取更多详细信息。 ... [详细]
author-avatar
那一世我给不了你的温柔
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有