使用DbProviderFactory达到多数据库访问的目的
这是一个说明如果使用DbProviderFactory来达到实现多数据库访问的文章,支持对ACCESS,SQL SERVER,ORACLE,SQLite等数据库的访问,在读取数据上使用DataReader但统一返回DataTable实例,支持以泛型的方式取得单个数据,并支持在有事务的情况下一次运行多条SQL语句.代码中关于参数缓存是抄袭了蛙蛙池塘曾发布过的一个数据库访问组件,不过在日常开发中,我一直没有用上.代码中有大量注释,且没有难懂的东西,应该都可以看懂,希望对大家有所帮助.如果存在安全性或性能问题,也希望大家指出来.代码中附带了三个数据库分页代码,SQL SERVER分页需要一个存储过程支持,及附带了一个显示分页页数的代码.使用时需要在web.config里面进入配置一下,如下>:
<connectionStrings>
<add name="ConnLink" connectionString="数据库连接驱动字符串" providerName="如:System.Data.SQLite"/>
</connectionStrings>
源程序下载地址:下载地址
下面是代码:
Code
1/**//**************************************************
2 * 文 件 名:dbbase.cs
3 * Copyright(c) 2009-2010
4 * 文件编号:001
5 * 创 建 人:晴天水族
6 * 日 期:2009-01-23
7 * 修 改 人:
8 * 修改日期:
9 * 备注描述:数据工厂类
10 * 支持ACCESS,SQL SERVER,ORACLE,SQLite
11 *************************************************/
12" 导入的命名空间 "#region " 导入的命名空间 "
13using System;
14using System.Data;
15using System.Data.SqlClient;
16using System.Data.Common;
17using System.Configuration;
18using System.Collections;
19using System.Text;
20using System.Data.SQLite; //添加对SQLite数据库的支持
21#endregion
22
23" 新建通用的数据库操作命名空间,支持ACCESS,SQL SERVER,ORACLE,SQLite "#region " 新建通用的数据库操作命名空间,支持ACCESS,SQL SERVER,ORACLE,SQLite "
24namespace dbbase
25{
26
27 "操作数据库类"#region "操作数据库类"
28 public class dbbases : IDisposable
29 {
30 /**//// <summary>
31 /// 安全类型的集合
32 /// </summary>
33 private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
34 /**//// <summary>
35 /// 下面两个是静态变量
36 /// </summary>
37 private static readonly string strs = ConfigurationManager.ConnectionStrings["ConnLink"].ConnectionString;
38 private static readonly string pdn = ConfigurationManager.ConnectionStrings["ConnLink"].ProviderName;
39
40 /**//// <summary>
41 /// 属性用于接收数据的存取类型 及识别用户所启用的数据库
42 /// </summary>
43 private string providername;
44 /**//// <summary>
45 /// 各种数据库的连接字符串
46 /// </summary>
47 private string connstring;
48
49 " 带参和不带参的构造函数 "#region " 带参和不带参的构造函数 "
50 /**//// <summary>
51 /// 默认构造函数,有重载
52 /// </summary>
53 public dbbases()
54 {
55 this.providername = pdn; //使用的数据驱动类,默认
56 this.connstring = strs; //连接数据库的字符串,默认
57 }
58
59 /**//// <summary>
60 /// 初始构造函数
61 /// </summary>
62 /// <param name="provider">数据驱动类型[SqlClient|Access|Orarl|SQLite]</param>
63 /// <param name="links">数据库的连接字符串</param>
64 public dbbases(string provider, string links)
65 {
66 this.providername = provider; //使用的数据驱动类
67 this.connstring = links; //连接数据库的字符串
68 }
69 #endregion
70
71 /**//// <summary>
72 /// 析构函数
73 /// </summary>
74 ~dbbases()
75 {
76 CloseCon(); //热行清理
77 }
78
79
80 /**//// <summary>
81 /// 检测当前数据库连接状态
82 /// </summary>
83 /// <returns></returns>
84 public string isConnstate()
85 {
86 if (cmd != null)
87 {
88 return cmd.Connection.State.ToString();
89 }
90 return "变量已清除";
91 }
92
93 "isclose属性,默认0指进行清理,1为不进行清理,可以用于多次循环之中,避免多次开关数据库"#region "isclose属性,默认0指进行清理,1为不进行清理,可以用于多次循环之中,避免多次开关数据库"
94 /**//// <summary>
95 /// 是否进行各项数据库连接器的清理工作
96 /// </summary>
97 /// <returns></returns>
98 private int isclose = 0;
99 public int IsClose
100 {
101 get
102 {
103 return isclose;
104 }
105 set
106 {
107 isclose = value;
108 }
109 }
110 #endregion
111
112 " 分页记录反回变量 "#region " 分页记录反回变量 "
113 private int allpage = 0; /**////分页函数中记录共有多少页的变量
114 public int Allpage
115 {
116 get { return allpage; }
117 }
118
119 private int allrecord = 0; /**////分页函数中记录菜有数据总量的变量
120 public int Allrecord
121 {
122 get { return allrecord; }
123 }
124 #endregion
125
126 " 数据库操作对像的属性[Adapter|Command|Begintransaction] "#region " 数据库操作对像的属性[Adapter|Command|Begintransaction] "
127 /**//// <summary>
128 /// 属性DbDataAdapter
129 /// </summary>
130 private DbDataAdapter adp;
131
132 /**//// <summary>
133 /// 属性SqlCommand
134 /// </summary>
135 private DbCommand cmd;
136
137 /**//// <summary>
138 /// 事务
139 /// </summary>
140 private DbTransaction Tran;
141 #endregion
142
143 " CloseCon() 关闭相关的数据库连接 "#region " CloseCon() 关闭相关的数据库连接 "
144 /**//// <summary>
145 /// 关闭数据库连接
146 /// </summary>
147 public void CloseCon()
148 {
149 if (cmd != null)
150 {
151 if (cmd.Connection.State != ConnectionState.Closed)
152 {
153 cmd.Connection.Close();
154 }
155 cmd.Dispose();
156 cmd = null;
157 }
158
159 if (adp != null)
160 {
161 adp.Dispose();
162 adp = null;
163 }
164
165 if (Tran != null)
166 {
167 Tran.Dispose();
168 Tran = null;
169 }
170
171 //GC.Collect(); ///强制对所有代进行垃圾回收
172 }
173 #endregion
174
175 "getFace() 创建工厂对像"#region "getFace() 创建工厂对像"
176 /**//// <summary>
177 /// 创建工厂对像
178 /// </summary>
179 /// <returns>DbProviderFactory</returns>
180 public DbProviderFactory getFace()
181 {
182 DbProviderFactory fact = null;
183 if (providername == "System.Data.SQLite")
184 {
185 fact = SQLiteFactory.Instance; //SQLite数据库创建数据工厂类
186 }
187 else
188 {
189 fact = DbProviderFactories.GetFactory(providername); //获得当前所调定的数据源存取类型
190 }
191 return fact;
192 }
193 #endregion
194
195 " 创建CMD对像,以供其它对像使用 "#region " 创建CMD对像,以供其它对像使用 "
196 /**//// <summary>
197 /// 创建CMD对像
198 /// </summary>
199 /// <returns>DbComand对像实例</returns>
200 private DbCommand CreateDbCommand()
201 {
202 DbProviderFactory fact = getFace(); //工厂对像
203 DbConnection conn = fact.CreateConnection(); //创建Connection对像
204 conn.ConnectionString = connstring; //设定Connection对像的连接字符串
205 cmd = conn.CreateCommand(); //使用 conn 的函数 CreateCommand() 创建Command对像
206 return cmd; //返回Command对像
207 }
208 #endregion
209
210 " RemoveParames清除CMD的参数 及存储过程的参数缓存 "#region " RemoveParames清除CMD的参数 及存储过程的参数缓存 "
211 /**//// <summary>
212 /// 清除参数
213 /// </summary>
214 /// <param name="cmd">DbCommand的对像</param>
215 private void RemoveParams(DbCommand cmd)
216 {
217 while (cmd.Parameters.Count > 0)
218 {
219 cmd.Parameters.RemoveAt(0);
220 }
221 }
222
223 /**//// <summary>
224 /// 从缓存中初使化SQL或存储过程的参数
225 /// </summary>
226 /// <param name="cmd">Command对像</param>
227 /// <returns>布尔值</returns>
228 public bool initParametersFromCache(DbCommand cmd)
229 {
230 DbParameter[] parms = GetCachedParameters(string.Format("{0}{1}", cmd.Connection.ConnectionString, cmd.CommandText));
231 if (parms == null)
232 return false;
233 for (int i = 0; i < parms.Length; i++)
234 {
235 cmd.Parameters.Add(parms[i]);
236 }
237 return true;
238 }
239
240 public static void CacheParameters(string cacheKey, params DbParameter[] cmdParms)
241 {
242 parmCache[cacheKey] = cmdParms;
243 }
244
245 /**//// <summary>
246 /// 查找缓存中的变量
247 /// </summary>
248 /// <param name="cacheKey">缓存名称</param>
249 /// <returns>DbParameter</returns>
250 public DbParameter[] GetCachedParameters(string cacheKey)
251 {
252 DbParameter[] cachedParms = (DbParameter[])parmCache[cacheKey]; //parmCache 本程序第18行,安全类型的HASHtable
253
254 if (cachedParms == null)
255 return null;
256
257 DbParameter[] clonedParms = new DbParameter[cachedParms.Length];
258
259 for (int i = 0, j = cachedParms.Length; i < j; i++)
260 {
261 clonedParms[i] = (DbParameter)((ICloneable)cachedParms[i]).Clone();
262 }
263
264 return clonedParms;
265 }
266
267 /**//// <summary>
268 /// 缓存参数
269 /// </summary>
270 /// <param name="cmd">DbCommand</param>
271 public void CachedParameters(DbCommand cmd)
272 {
273 DbParameterCollection paramColl = cmd.Parameters;
274 DbParameter[] parms = new DbParameter[paramColl.Count];
275 for (int i = 0; i < paramColl.Count; i++)
276 {
277 parms[i] = paramColl[i];
278 }
279
280 CacheParameters(string.Format("{0}{1}", cmd.Connection.ConnectionString, cmd.CommandText), parms);
281 }
282
283
284 #endregion
285
286 " ProTxtCmd创建操作存储过程与SQL的CMD对像 "#region " ProTxtCmd创建操作存储过程与SQL的CMD对像 "
287 /**//// <summary>
288 /// 创建操作存储过程与SQL的CMD对像
289 /// </summary>
290 /// <param name="pronames">存储过程或SQL语句</param>
291 /// <param name="sid">识别ID</param>
292 /// <returns>cmd</returns>
293 private DbCommand ProTxtCmd(string proSqls, Byte sid)
294 {
295 cmd = CreateDbCommand(); //创建CMD对像
296 if (sid == 0)
297 {
298 cmd.CommandType = CommandType.Text; //设置SQL语句
299 }
300 else
301 {
302 cmd.CommandType = CommandType.StoredProcedure; //设置 cmd 的操作命令方式,此处为存储过程
303 }
304
305 cmd.CommandText = proSqls; //设置 存储过程名或SQL语句
306 return cmd;
307 }
308 #endregion
309
310 "executeRunSqlArray 执行多条SQL语句,有事务,批量删除等,传递一个数组"#region "executeRunSqlArray 执行多条SQL语句,有事务,批量删除等,传递一个数组"
311 /**//// <summary>
312 /// 执行多条SQL语句,有事务
313 /// </summary>
314 /// <param name="sqllist">SQL语句集合数组</param>
315 /// <returns>Boolean</returns>
316 public bool executeRunSqlArray(string[] sqllist)
317 {
318 cmd = CreateDbCommand(); //创建CMD对像
319 try
320 {
321 if (cmd.Connection.State != ConnectionState.Open)
322 {
323 cmd.Connection.Open();
324 }
325 Tran = cmd.Connection.BeginTransaction(); //新增事务
326 cmd.Transaction = Tran; //事务
327 for (int i = 0; i < sqllist.Length; i++)
328 {
329 string sql = sqllist[i].ToString();
330 if (sql.Trim().Length > 1)
331 {
332 cmd.CommandText = sql;
333 cmd.ExecuteNonQuery();
334 }
335 }
336 Tran.Commit();
337 }
338 catch (DbException ex)
339 {
340 Tran.Rollback();
341 printEx(ex, 1);
342 return false;
343 }
344 finally
345 {
346 if (this.isclose == 0) //默认清理
347 {
348 CloseCon(); //热行清理
349 }
350 }
351
352 return true;
353
354 }
355 #endregion
356
357 " getdt 从SQL语句或存储过程中返回DataTable "#region " getdt 从SQL语句或存储过程中返回DataTable "
358 /**//// <summary>
359 /// 返回SQLS中的dt
360 /// </summary>
361 /// <param name="sqlsPro">SQL语句</param>
362 /// <param name="parames">SQL语句参数</param>
363 /// <param name="sid">识别码,0为SQL语句,1为存储过程</param>
364 /// <returns>DateTable</returns>
365 public DataTable getdt(string sqlsPro, DbParameter[] parames, int sid)
366 {
367 DataTable dt = new DataTable();
368 DbDataReader dr = null;
369
370 if (sid == 0) //SQL语句
371 {
372 cmd = ProTxtCmd(sqlsPro, 0);
373 }
374 else //存储过程
375 {
376 cmd = ProTxtCmd(sqlsPro, 1);
377 }
378
379 if (parames != null && parames.Length > 0)
380 {
381 foreach (DbParameter param in parames)
382 if (param.Value != null)
383 cmd.Parameters.Add(param);
384 }
385
386 try
387 {
388 if (cmd.Connection.State != ConnectionState.Open)
389 {
390 cmd.Connection.Open();
391 }
392 dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
393 if (dr.HasRows)
394 {
395 dt.Load(dr);
396 dr.Close();
397 dr = null;
398 }
399 }
400 catch (DbException ex)
401 {
402 dr.Close();
403 dr = null;
404 printEx(ex, 1);
405 }
406 finally
407 {
408 if (this.isclose == 0) //默认清理
409 {
410 if (parames != null)
411 {
412 RemoveParams(cmd);
413 cmd.Parameters.Clear();
414 }
415 CloseCon(); //热行清理
416 }
417 }
418 return dt;
419 }
420 #endregion
421
422 " runsql 执行SQL语句 "#region " runsql 执行SQL语句 "
423 /**//// <summary>
424 /// 运行SQL语句
425 /// </summary>
426 /// <param name="sqlsPro">sql语句</param>
427 /// <param name="parames">SQL语句参数</param>
428 /// <param name="sid">识别ID</param>
429 /// <returns>int</returns>
430 public int runsql(string sqlsPro, DbParameter[] parames, int sid)
431 {
432 int rsInt = 0;
433
434 cmd = null;
435
436 if (sid == 0) //SQL语句
437 {
438 cmd = ProTxtCmd(sqlsPro, 0);
439 }
440 else //存储过程
441 {
442 cmd = ProTxtCmd(sqlsPro, 1);
443 }
444
445 if (parames != null && parames.Length > 0)
446 {
447 foreach (DbParameter param in parames)
448 if (param.Value != null)
449 cmd.Parameters.Add(param);
450 }
451
452 try
453 {
454 if (cmd.Connection.State != ConnectionState.Open)
455 {
456 cmd.Connection.Open();
457 }
458
459 rsInt = cmd.ExecuteNonQuery();
460 }
461 catch (DbException ex)
462 {
463 printEx(ex, 1);
464 }
465 finally
466 {
467 if (this.isclose == 0) //默认清理
468 {
469 if (parames != null)
470 {
471 RemoveParams(cmd);
472 cmd.Parameters.Clear();
473 }
474 CloseCon(); //热行清理
475 }
476 }
477
478 return rsInt;
479
480 }
481 #endregion
482
483 " getSca 泛型,取得单个数据ExecuteScalar,适用于SQL语句及存储过程 "#region " getSca 泛型,取得单个数据ExecuteScalar,适用于SQL语句及存储过程 "
484 /**//// <summary>
485 /// 取得单个数据 (注意如果取整型数据请使用long代替T)
486 /// </summary>
487 /// <typeparam name="T">泛型所替换的数据类型</typeparam>
488 /// <param name="sqlsPro">sql语句</param>
489 /// <param name="parames">SQL语句的参数</param>
490 /// <param name="sid">识别ID,0为SQL语句,1为存储过程</param>
491 /// <returns></returns>
492 public T getSca<T>(string sqlsPro, DbParameter[] parames, int sid)
493 {
494 cmd = null;
495
496 if (sid == 0) //SQL语句
497 {
498 cmd = ProTxtCmd(sqlsPro, 0);
499 }
500 else //存储过程
501 {
502 cmd = ProTxtCmd(sqlsPro, 1);
503 }
504
505 if (parames != null && parames.Length > 0)
506 {
507 foreach (DbParameter param in parames)
508 if (param.Value != null)
509 cmd.Parameters.Add(param);
510 }
511 T Tstr = default(T); /**////泛型变量
512 try
513 {
514 if (cmd.Connection.State != ConnectionState.Open)
515 {
516 cmd.Connection.Open();
517 }
518
519 if (System.DBNull.Value != cmd.ExecuteScalar())
520 {
521 Tstr = (T)cmd.ExecuteScalar(); /**////读取第一行第一列
522 }
523
524 }
525 catch (DbException ex)
526 {
527 printEx(ex, 0);
528 return default(T);
529 }
530 finally
531 {
532 if (this.isclose == 0) //默认清理
533 {
534 if (parames != null)
535 {
536 RemoveParams(cmd);
537 cmd.Parameters.Clear();
538 }
539 CloseCon(); //热行清理
540 }
541 }
542
543 return Tstr;
544
545 }
546 #endregion
547
548 " 使用Adapter填充DataTable "#region " 使用Adapter填充DataTable "
549 /**//// <summary>
550 /// 返回SQLS中的dt
551 /// </summary>
552 /// <param name="sqlsPro">SQL语句</param>
553 /// <param name="parames">SQL语句参数</param>
554 /// <param name="sid">识别码,0为SQL语句,1为存储过程</param>
555 /// <returns>DateTable</returns>
556 public DataTable getAdpdt(string sqlsPro, DbParameter[] parames, Byte sid)
557 {
558 DbProviderFactory dbfactory = getFace(); //取得数据库工厂对像
559
560 adp = dbfactory.CreateDataAdapter();
561
562 if (sid == 0) //SQL语句
563 {
564 cmd = ProTxtCmd(sqlsPro, 0);
565 }
566 else //存储过程
567 {
568 cmd = ProTxtCmd(sqlsPro, 1);
569 }
570
571 if (parames != null && parames.Length > 0)
572 {
573 foreach (DbParameter param in parames)
574 if (param.Value != null)
575 cmd.Parameters.Add(param);
576 }
577
578 adp.SelectCommand = cmd;
579 DataTable dt = new DataTable();
580 try
581 {
582 adp.Fill(dt);
583 }
584 catch (DbException ex)
585 {
586 printEx(ex, 1);
587 }
588 finally
589 {
590 if (this.isclose == 0) //默认清理
591 {
592 if (parames != null)
593 {
594 RemoveParams(cmd);
595 cmd.Parameters.Clear();
596 }
597
598 CloseCon(); //热行清理
599 }
600 }
601 return dt;
602 }
603 #endregion
604
605 " Pagination_dt 分页,适用于SQL SERVER数据库 "#region " Pagination_dt 分页,适用于SQL SERVER数据库 "
606 /**//// <summary>
607 /// 分页函数,返回dt
608 /// </summary>
609 /// <param name="table_name">需要分页显示的表名</param>
610 /// <param name="key">表的主键,必须唯一性</param>
611 /// <param name="orderstr">排序字段如f_Name asc或f_name desc(注意只能有一个排序字段)</param>
612 /// <param name="cpage">当前页</param>
613 /// <param name="psize">每页大小</param>
614 /// <param name="fieles">显示的字段列表</param>
615 /// <param name="filter">条件语句,不加where</param>
616 /// <param name="g_str">分组字段</param> 以前都不再使用
617 /// <param name="pro_name">存储过程名</param>
618 /// <returns>返回内存表</returns>
619 public DataTable Pagination_dt(string table_name, string key, string orderstr, int cpage, int psize, string fieles, string filter, string g_str, string pro_name)
620 {
621
622 DataTable dt = new DataTable();
623
624 SqlCommand cmd = (SqlCommand)ProTxtCmd(pro_name, 1);
625
626 SqlParameter[] parames = { new SqlParameter("@Tables", SqlDbType.VarChar, 50), new SqlParameter("@PrimaryKey", SqlDbType.VarChar, 10), new SqlParameter("@Sort", SqlDbType.VarChar, 50), new SqlParameter("@CurrentPage", SqlDbType.Int, 4), new SqlParameter("@PageSize", SqlDbType.Int, 4), new SqlParameter("@fields", SqlDbType.VarChar, 1000), new SqlParameter("@Filter", SqlDbType.VarChar, 1000), new SqlParameter("@Group", SqlDbType.VarChar, 1000) };
627
628 parames[0].Value = table_name;
629 parames[1].Value = key;
630 parames[2].Value = orderstr;
631 parames[3].Value = cpage;
632 parames[4].Value = psize;
633 parames[5].Value = fieles;
634 parames[6].Value = filter;
635 parames[7].Value = g_str;
636
637 foreach (SqlParameter parameter in parames) /**////添加输入参数集合
638 {
639 cmd.Parameters.Add(parameter);
640 }
641
642 SqlParameter s1 = cmd.Parameters.Add(new SqlParameter("@TotalPage", SqlDbType.Int));
643 SqlParameter s2 = cmd.Parameters.Add(new SqlParameter("@TotalRecord", SqlDbType.Int)); /**////返回值
644 s1.Direction = ParameterDirection.Output;
645 s2.Direction = ParameterDirection.Output;
646
647 DbDataReader dr = null;
648
649 try
650 {
651 if (cmd.Connection.State != ConnectionState.Open)
652 {
653 cmd.Connection.Open();
654 }
655
656 dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); //关闭数据库
657 if (dr.HasRows)
658 {
659 dt.Load(dr);
660 dr.Close();
661 dr.Dispose();
662
663 if (cmd.Parameters["@TotalRecord"].Value != System.DBNull.Value)
664 {
665 allrecord = int.Parse(cmd.Parameters["@TotalRecord"].Value.ToString()); /**////返回总记录数
666 }
667
668
669 if (cmd.Parameters["@TotalPage"].Value != System.DBNull.Value)
670 {
671 allpage = int.Parse(cmd.Parameters["@TotalPage"].Value.ToString()); /**////返回首页数
672 }
673 }
674 }
675 catch (DbException ex)
676 {
677 dr.Close();
678 dr = null;
679 printEx(ex, 1);
680 }
681 finally
682 {
683 if (parames != null)
684 {
685 RemoveParams(cmd);
686 cmd.Parameters.Clear();
687 }
688 CloseCon(); //热行清理
689 }
690
691 return dt;
692 }
693 #endregion
694
695 " Access_dt 分页,适用于ACCESS及其其它使用SQL语句的分页 "#region " Access_dt 分页,适用于ACCESS及其其它使用SQL语句的分页 "
696 /**//// <summary>
697 /// SQL语句分页函数,返回dt
698 /// </summary>
699 /// <param name="table_name">需要分页显示的表名</param>
700 /// <param name="key">表的主键ID,且只能为ID必须唯一性</param>
701 /// <param name="orderstr">排序字段如id ASC,addTimes DESC或id DESC,addTimes ASC(可以有多个排序字段)</param>
702 /// <param name="cpage">当前页</param>
703 /// <param name="psize">每页大小</param>
704 /// <param name="fieles">显示的字段列表</param>
705 /// <param name="filter">条件语句,不加where</param>
706 /// <param name="isDesc">排序方式[true=desc倒序|false=asc顺序]</param>
707 /// <param name="allrecordsqls">客户端传来的计算总记录的SQL语句</param>
708 /// <param name="sql">客户端发来的分页SQL语句</param>
709 /// <returns>返回内存表</returns>
710 public DataTable Access_dt(string table_name, string key, string orderstr, int cpage, int psize, string fieles, string filter, bool isDesc, string allrecordsqls, string sql)
711 {
712 //先计算总记录,再计算总页数
713 string allCordSql = null;
714 if (filter == null) //不存在WHERE子句
715 {
716 allCordSql = "SELECT COUNT(" + key + ") FROM " + table_name + "";
717 }
718 else
719 {
720 allCordSql = "SELECT COUNT(" + key + ") FROM " + table_name + " WHERE " + filter + "";
721 }
722
723 if (allrecordsqls == null)
724 {
725 allrecord = getSca<int>(allCordSql, null, 0); /**////返回总记录数
726 }
727 else
728 {
729 allrecord = getSca<int>(allrecordsqls, null, 0); /**////返回总记录数
730 }
731
732 if (allrecord % psize == 0)
733 {
734 allpage = allrecord / psize; //返回总页数
735 }
736 else
737 {
738 allpage = allrecord / psize + 1; //返回总页数
739 }
740
741 string sqls = null;
742
743 if (isDesc) //倒序[从大到小]
744 {
745 if (filter == null) //不存在WHERE子句
746 {
747 if (cpage == 1)
748 {
749 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " ORDER BY " + orderstr + ""; //第一页
750 }
751 else
752 {
753 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + key + "<(SELECT MIN(" + key + ") FROM (SELECT TOP " + (cpage - 1) * psize + " " + key + " FROM " + table_name + " ORDER BY " + orderstr + ") as T) ORDER BY " + orderstr + ""; //非第一页
754 }
755 }
756 else
757 {
758 if (cpage == 1)
759 {
760 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + filter + " ORDER BY " + orderstr + ""; //第一页
761 }
762 else
763 {
764 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + filter + " AND " + key + "<(SELECT MIN(" + key + ") FROM (SELECT TOP " + (cpage - 1) * psize + " " + key + " FROM " + table_name + " WHERE " + filter + " ORDER BY " + orderstr + ") as T) ORDER BY " + orderstr + ""; //非第一页
765 }
766 }
767 }
768 else //顺序[从小到大]
769 {
770 if (filter == null) //不存在WHERE子句
771 {
772 if (cpage == 1)
773 {
774 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " ORDER BY " + orderstr + ""; //第一页
775 }
776 else
777 {
778 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + key + ">(SELECT MAX(" + key + ") FROM (SELECT TOP " + (cpage - 1) * psize + " " + key + " FROM " + table_name + " ORDER BY " + orderstr + ") as T) ORDER BY " + orderstr + ""; //非第一页
779 }
780 }
781 else
782 {
783 if (cpage == 1)
784 {
785 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + filter + " ORDER BY " + orderstr + ""; //第一页
786 }
787 else
788 {
789 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + filter + " AND " + key + ">(SELECT MAX(" + key + ") FROM (SELECT TOP " + (cpage - 1) * psize + " " + key + " FROM " + table_name + " WHERE " + filter + " ORDER BY " + orderstr + ") as T) ORDER BY " + orderstr + ""; //非第一页
790 }
791 }
792 }
793 //到此构造分页语句完成
794
795 DataTable dt = new DataTable();
796
797 if (sql == null) //客户端没有传入SQL语句
798 {
799 dt = this.getdt(sqls.ToString(), null, 0);
800 }
801 else //有传入
802 {
803 dt = this.getdt(sql, null, 0);
804 }
805
806 return dt;
807
808 }
809 #endregion
810
811 " SQLite分页,只适用于SQLite数据库"#region " SQLite分页,只适用于SQLite数据库"
812 /**//// <param name="tablename">需要分页显示的表名</param>
813 /// <param name="key">表的主键ID,且只能为ID必须唯一性</param>
814 /// <param name="orderstr">排序字段如id ASC,addTimes DESC或id DESC,addTimes ASC(可以有多个排序字段)</param>
815 /// <param name="cpage">当前页</param>
816 /// <param name="psize">每页大小</param>
817 /// <param name="fieles">显示的字段列表</param>
818 /// <param name="filter">条件语句,不加where</param>
819 /// <param name="allrecordsqls">客户端传来的计算总记录的SQL语句</param>
820 /// <param name="sql">客户端发来的分页SQL语句</param>
821 /// <returns>返回内存表</returns>
822 public DataTable SQLite_dt(string tablename, string key, string orderstr, int cpage, int psize, string fieles, string filter, string allrecordsqls, string sql)
823 {
824 //先计算总记录,再计算总页数
825 string allCordSql = null;
826 if (filter == null) //不存在WHERE子句
827 {
828 allCordSql = "SELECT COUNT([" + key + "]) FROM [" + tablename + "]";
829 }
830 else
831 {
832 allCordSql = "SELECT COUNT([" + key + "]) FROM [" + tablename + "] WHERE " + filter + "";
833 }
834
835 if (allrecordsqls == null)
836 {
837 allrecord = int.Parse(this.getSca<long>(allCordSql, null, 0).ToString()); /**////返回总记录数
838 }
839 else
840 {
841 allrecord = int.Parse(this.getSca<long>(allrecordsqls, null, 0).ToString()); /**////返回总记录数
842 }
843
844 if (allrecord % psize == 0)
845 {
846 allpage = allrecord / psize; //返回总页数
847 }
848 else
849 {
850 allpage = allrecord / psize + 1; //返回总页数
851 }
852
853 StringBuilder sqls = new StringBuilder("SELECT " + fieles + " FROM [" + tablename + "]");
854
855 if (filter != null) //不存在WHERE子句
856 {
857 sqls.Append(" WHERE " + filter + " "); //非第一页
858 }
859
860 if (cpage == 1)
861 {
862 sqls.Append(" ORDER BY " + orderstr + " LIMIT " + psize); //第一页
863 }
864 else
865 {
866 sqls.Append(" ORDER BY " + orderstr + " LIMIT " + (psize * cpage - psize) + "," + psize + ""); //非第一页
867 }
868
869 //到此构造分页语句完成 throw new Exception("出现异常:" + sqls.ToString());
870
871 DataTable dt = new DataTable();
872
873 if (sql == null) //客户端没有传入SQL语句
874 {
875 dt = this.getdt(sqls.ToString(), null, 0);
876 }
877 else //有传入
878 {
879 dt = this.getdt(sql, null, 0);
880 }
881
882 return dt;
883 }
884 #endregion
885
886 " IDisposable 成员 "#region " IDisposable 成员 "
887 /**//// <summary>
888 /// 强迫释放数据库连接
889 /// </summary>
890 public void Dispose()
891 {
892 Dispose(true);
893 }
894
895 /**//// <summary>
896 /// 类回收时,关闭数据库连接
897 /// </summary>
898 /// <param name="disposing"></param>
899 public void Dispose(bool disposing)
900 {
901 if (disposing)
902 {
903 CloseCon();
904 }
905 else
906 {
907 CloseCon();
908 }
909 }
910
911 #endregion
912
913 " showpage 显示分页数 "#region " showpage 显示分页数 "
914 /**//// <summary>
915 /// url调整
916 /// </summary>
917 /// <param name="str">网址</param>
918 /// <returns>string</returns>
919 public string joinchar(string str)
920 {
921 if (str == "")
922 {
923 return "";
924 }
925
926 if (str.IndexOf("?") < str.Length)
927 {
928 if (str.IndexOf("?") > 1)
929 {
930 if (str.IndexOf("&") < str.Length)
931 {
932 return str + "&";
933 }
934 else
935 {
936 return str;
937 }
938 }
939 else
940 {
941 return str + "?";
942 }
943 }
944
945 return str;
946 }
947
948 /**//// <summary>
949 /// 显示分页数
950 /// </summary>
951 /// <param name="total">记录数</param>
952 /// <param name="pagenum">每页个数</param>
953 /// <param name="current">当前页</param>
954 /// <param name="url">页面url</param>
955 /// <param name="unit">单位[条|个|位]</param>
956 /// <returns>string</returns>
957 public string showpage(int total, int pagenum, int current, string url, string unit)
958 {
959 StringBuilder str = new StringBuilder();
960 StringBuilder str1 = new StringBuilder();
961
962 int page = 1;
963 if (total % pagenum == 0)
964 {
965 page = total / pagenum;
966 }
967 else
968 {
969 page = total / pagenum + 1;
970 }
971 url = joinchar(url);
972
973 if (page > 10)
974 {
975 if (current <= 5)
976 {
977 for (int i = 1; i <= 9; i++)
978 {
979 if (i == current)
980 {
981 str.Append(" <b>[" + i + "]</b> ");
982 }
983 else
984 {
985 str.Append(" <a href='" + url + "page=" + i + "'>" + i + "</a> ");
986 }
987 }
988 str.Append("" + " <a href='" + url + "page=" + page + "'>" + page + "</a> ");
989 }
990 else if (current >= page - 4)
991 {
992 str.Append(" <a href='" + url + "page=1'>1</a> ");
993 for (int i = page - 8; i <= page; i++)
994 {
995 if (i == current)
996 {
997 str.Append(" <b>[" + i + "]</b> ");
998 }
999 else
1000 {
1001 str.Append(" <a href='" + url + "page=" + i + "'>" + i + "</a> ");
1002 }
1003 }
1004 }
1005 else
1006 {
1007 str.Append(" <a href='" + url + "page=1'>1</a> ");
1008 for (int i = current - 4; i <= current + 4; i++)
1009 {
1010 if (i == current)
1011 {
1012 str.Append(" <b>[" + i + "]</b> ");
1013 }
1014 else
1015 {
1016 str.Append(" <a href='" + url + "page=" + i + "'>" + i + "</a> ");
1017 }
1018 }
1019 str.Append("" + " <a href='" + url + "page=" + page + "'>" + page + "</a> ");
1020 }
1021 }
1022 else
1023 {
1024 for (int i = 1; i <= page; i++)
1025 {
1026 if (page != 1)
1027 {
1028 if (i == current)
1029 {
1030 str.Append(" <b>[" + i + "]</b> ");
1031 }
1032 else
1033 {
1034 str.Append(" <a href='" + url + "page=" + i + "'>" + i + "</a> ");
1035 }
1036 }
1037 }
1038 }
1039 int down = current + 1;
1040 int up = current - 1;
1041 if (page > 1)
1042 {
1043 if (current == 1)
1044 {
1045 str1.Append(" <a href='" + url + "page=2'>下一页</a>");
1046 }
1047 else if (current == page)
1048 {
1049 str1.Append(" <a href='" + url + "page=" + up.ToString() + "'>上一页</a>");
1050 }
1051 else
1052 {
1053 str1.Append(" <a href='" + url + "page=" + up.ToString() + "'>上一页</a> <a href='" + url + "page=" + down.ToString() + "'>下一页</a>");
1054 }
1055 }
1056 if (page == 0) { page = 1; }
1057
1058 return "页次:" + pagenum + "/" + current + "/" + page.ToString() + ",共<span id='rs_count'>" + total.ToString() + "</span>" + unit + " " + str1.ToString() + str.ToString();
1059 }
1060 #endregion
1061
1062 "printEx 打印异常"#region "printEx 打印异常"
1063 /**//// <summary>
1064 /// 打印异常
1065 /// </summary>
1066 /// <param name="ex">异常集合</param>
1067 /// <param name="id">是否显示错误</param>
1068 private void printEx(DbException e, int id)
1069 {
1070 if (this.isclose == 1) //如果isclose的值是1说明没有执行清理工作,所以在异常收集函数里面执行清理工作
1071 {
1072 CloseCon(); //热行清理
1073 }
1074 if (id == 1)
1075 {
1076 string errstr = "错误如下:<br />" + "出错信息:" + e.Message + "<br />" + "出错来源:" + e.Source + "<br />" + "程序:" + e.ErrorCode + "<br />异常方法:" + e.TargetSite;
1077 throw new Exception("出现异常:" + errstr);
1078 }
1079 }
1080 #endregion
1081
1082 }
1083 #endregion
1084
1085}
1086#endregion
1/**//**************************************************
2 * 文 件 名:dbbase.cs
3 * Copyright(c) 2009-2010
4 * 文件编号:001
5 * 创 建 人:晴天水族
6 * 日 期:2009-01-23
7 * 修 改 人:
8 * 修改日期:
9 * 备注描述:数据工厂类
10 * 支持ACCESS,SQL SERVER,ORACLE,SQLite
11 *************************************************/
12" 导入的命名空间 "#region " 导入的命名空间 "
13using System;
14using System.Data;
15using System.Data.SqlClient;
16using System.Data.Common;
17using System.Configuration;
18using System.Collections;
19using System.Text;
20using System.Data.SQLite; //添加对SQLite数据库的支持
21#endregion
22
23" 新建通用的数据库操作命名空间,支持ACCESS,SQL SERVER,ORACLE,SQLite "#region " 新建通用的数据库操作命名空间,支持ACCESS,SQL SERVER,ORACLE,SQLite "
24namespace dbbase
25{
26
27 "操作数据库类"#region "操作数据库类"
28 public class dbbases : IDisposable
29 {
30 /**//// <summary>
31 /// 安全类型的集合
32 /// </summary>
33 private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
34 /**//// <summary>
35 /// 下面两个是静态变量
36 /// </summary>
37 private static readonly string strs = ConfigurationManager.ConnectionStrings["ConnLink"].ConnectionString;
38 private static readonly string pdn = ConfigurationManager.ConnectionStrings["ConnLink"].ProviderName;
39
40 /**//// <summary>
41 /// 属性用于接收数据的存取类型 及识别用户所启用的数据库
42 /// </summary>
43 private string providername;
44 /**//// <summary>
45 /// 各种数据库的连接字符串
46 /// </summary>
47 private string connstring;
48
49 " 带参和不带参的构造函数 "#region " 带参和不带参的构造函数 "
50 /**//// <summary>
51 /// 默认构造函数,有重载
52 /// </summary>
53 public dbbases()
54 {
55 this.providername = pdn; //使用的数据驱动类,默认
56 this.connstring = strs; //连接数据库的字符串,默认
57 }
58
59 /**//// <summary>
60 /// 初始构造函数
61 /// </summary>
62 /// <param name="provider">数据驱动类型[SqlClient|Access|Orarl|SQLite]</param>
63 /// <param name="links">数据库的连接字符串</param>
64 public dbbases(string provider, string links)
65 {
66 this.providername = provider; //使用的数据驱动类
67 this.connstring = links; //连接数据库的字符串
68 }
69 #endregion
70
71 /**//// <summary>
72 /// 析构函数
73 /// </summary>
74 ~dbbases()
75 {
76 CloseCon(); //热行清理
77 }
78
79
80 /**//// <summary>
81 /// 检测当前数据库连接状态
82 /// </summary>
83 /// <returns></returns>
84 public string isConnstate()
85 {
86 if (cmd != null)
87 {
88 return cmd.Connection.State.ToString();
89 }
90 return "变量已清除";
91 }
92
93 "isclose属性,默认0指进行清理,1为不进行清理,可以用于多次循环之中,避免多次开关数据库"#region "isclose属性,默认0指进行清理,1为不进行清理,可以用于多次循环之中,避免多次开关数据库"
94 /**//// <summary>
95 /// 是否进行各项数据库连接器的清理工作
96 /// </summary>
97 /// <returns></returns>
98 private int isclose = 0;
99 public int IsClose
100 {
101 get
102 {
103 return isclose;
104 }
105 set
106 {
107 isclose = value;
108 }
109 }
110 #endregion
111
112 " 分页记录反回变量 "#region " 分页记录反回变量 "
113 private int allpage = 0; /**////分页函数中记录共有多少页的变量
114 public int Allpage
115 {
116 get { return allpage; }
117 }
118
119 private int allrecord = 0; /**////分页函数中记录菜有数据总量的变量
120 public int Allrecord
121 {
122 get { return allrecord; }
123 }
124 #endregion
125
126 " 数据库操作对像的属性[Adapter|Command|Begintransaction] "#region " 数据库操作对像的属性[Adapter|Command|Begintransaction] "
127 /**//// <summary>
128 /// 属性DbDataAdapter
129 /// </summary>
130 private DbDataAdapter adp;
131
132 /**//// <summary>
133 /// 属性SqlCommand
134 /// </summary>
135 private DbCommand cmd;
136
137 /**//// <summary>
138 /// 事务
139 /// </summary>
140 private DbTransaction Tran;
141 #endregion
142
143 " CloseCon() 关闭相关的数据库连接 "#region " CloseCon() 关闭相关的数据库连接 "
144 /**//// <summary>
145 /// 关闭数据库连接
146 /// </summary>
147 public void CloseCon()
148 {
149 if (cmd != null)
150 {
151 if (cmd.Connection.State != ConnectionState.Closed)
152 {
153 cmd.Connection.Close();
154 }
155 cmd.Dispose();
156 cmd = null;
157 }
158
159 if (adp != null)
160 {
161 adp.Dispose();
162 adp = null;
163 }
164
165 if (Tran != null)
166 {
167 Tran.Dispose();
168 Tran = null;
169 }
170
171 //GC.Collect(); ///强制对所有代进行垃圾回收
172 }
173 #endregion
174
175 "getFace() 创建工厂对像"#region "getFace() 创建工厂对像"
176 /**//// <summary>
177 /// 创建工厂对像
178 /// </summary>
179 /// <returns>DbProviderFactory</returns>
180 public DbProviderFactory getFace()
181 {
182 DbProviderFactory fact = null;
183 if (providername == "System.Data.SQLite")
184 {
185 fact = SQLiteFactory.Instance; //SQLite数据库创建数据工厂类
186 }
187 else
188 {
189 fact = DbProviderFactories.GetFactory(providername); //获得当前所调定的数据源存取类型
190 }
191 return fact;
192 }
193 #endregion
194
195 " 创建CMD对像,以供其它对像使用 "#region " 创建CMD对像,以供其它对像使用 "
196 /**//// <summary>
197 /// 创建CMD对像
198 /// </summary>
199 /// <returns>DbComand对像实例</returns>
200 private DbCommand CreateDbCommand()
201 {
202 DbProviderFactory fact = getFace(); //工厂对像
203 DbConnection conn = fact.CreateConnection(); //创建Connection对像
204 conn.ConnectionString = connstring; //设定Connection对像的连接字符串
205 cmd = conn.CreateCommand(); //使用 conn 的函数 CreateCommand() 创建Command对像
206 return cmd; //返回Command对像
207 }
208 #endregion
209
210 " RemoveParames清除CMD的参数 及存储过程的参数缓存 "#region " RemoveParames清除CMD的参数 及存储过程的参数缓存 "
211 /**//// <summary>
212 /// 清除参数
213 /// </summary>
214 /// <param name="cmd">DbCommand的对像</param>
215 private void RemoveParams(DbCommand cmd)
216 {
217 while (cmd.Parameters.Count > 0)
218 {
219 cmd.Parameters.RemoveAt(0);
220 }
221 }
222
223 /**//// <summary>
224 /// 从缓存中初使化SQL或存储过程的参数
225 /// </summary>
226 /// <param name="cmd">Command对像</param>
227 /// <returns>布尔值</returns>
228 public bool initParametersFromCache(DbCommand cmd)
229 {
230 DbParameter[] parms = GetCachedParameters(string.Format("{0}{1}", cmd.Connection.ConnectionString, cmd.CommandText));
231 if (parms == null)
232 return false;
233 for (int i = 0; i < parms.Length; i++)
234 {
235 cmd.Parameters.Add(parms[i]);
236 }
237 return true;
238 }
239
240 public static void CacheParameters(string cacheKey, params DbParameter[] cmdParms)
241 {
242 parmCache[cacheKey] = cmdParms;
243 }
244
245 /**//// <summary>
246 /// 查找缓存中的变量
247 /// </summary>
248 /// <param name="cacheKey">缓存名称</param>
249 /// <returns>DbParameter</returns>
250 public DbParameter[] GetCachedParameters(string cacheKey)
251 {
252 DbParameter[] cachedParms = (DbParameter[])parmCache[cacheKey]; //parmCache 本程序第18行,安全类型的HASHtable
253
254 if (cachedParms == null)
255 return null;
256
257 DbParameter[] clonedParms = new DbParameter[cachedParms.Length];
258
259 for (int i = 0, j = cachedParms.Length; i < j; i++)
260 {
261 clonedParms[i] = (DbParameter)((ICloneable)cachedParms[i]).Clone();
262 }
263
264 return clonedParms;
265 }
266
267 /**//// <summary>
268 /// 缓存参数
269 /// </summary>
270 /// <param name="cmd">DbCommand</param>
271 public void CachedParameters(DbCommand cmd)
272 {
273 DbParameterCollection paramColl = cmd.Parameters;
274 DbParameter[] parms = new DbParameter[paramColl.Count];
275 for (int i = 0; i < paramColl.Count; i++)
276 {
277 parms[i] = paramColl[i];
278 }
279
280 CacheParameters(string.Format("{0}{1}", cmd.Connection.ConnectionString, cmd.CommandText), parms);
281 }
282
283
284 #endregion
285
286 " ProTxtCmd创建操作存储过程与SQL的CMD对像 "#region " ProTxtCmd创建操作存储过程与SQL的CMD对像 "
287 /**//// <summary>
288 /// 创建操作存储过程与SQL的CMD对像
289 /// </summary>
290 /// <param name="pronames">存储过程或SQL语句</param>
291 /// <param name="sid">识别ID</param>
292 /// <returns>cmd</returns>
293 private DbCommand ProTxtCmd(string proSqls, Byte sid)
294 {
295 cmd = CreateDbCommand(); //创建CMD对像
296 if (sid == 0)
297 {
298 cmd.CommandType = CommandType.Text; //设置SQL语句
299 }
300 else
301 {
302 cmd.CommandType = CommandType.StoredProcedure; //设置 cmd 的操作命令方式,此处为存储过程
303 }
304
305 cmd.CommandText = proSqls; //设置 存储过程名或SQL语句
306 return cmd;
307 }
308 #endregion
309
310 "executeRunSqlArray 执行多条SQL语句,有事务,批量删除等,传递一个数组"#region "executeRunSqlArray 执行多条SQL语句,有事务,批量删除等,传递一个数组"
311 /**//// <summary>
312 /// 执行多条SQL语句,有事务
313 /// </summary>
314 /// <param name="sqllist">SQL语句集合数组</param>
315 /// <returns>Boolean</returns>
316 public bool executeRunSqlArray(string[] sqllist)
317 {
318 cmd = CreateDbCommand(); //创建CMD对像
319 try
320 {
321 if (cmd.Connection.State != ConnectionState.Open)
322 {
323 cmd.Connection.Open();
324 }
325 Tran = cmd.Connection.BeginTransaction(); //新增事务
326 cmd.Transaction = Tran; //事务
327 for (int i = 0; i < sqllist.Length; i++)
328 {
329 string sql = sqllist[i].ToString();
330 if (sql.Trim().Length > 1)
331 {
332 cmd.CommandText = sql;
333 cmd.ExecuteNonQuery();
334 }
335 }
336 Tran.Commit();
337 }
338 catch (DbException ex)
339 {
340 Tran.Rollback();
341 printEx(ex, 1);
342 return false;
343 }
344 finally
345 {
346 if (this.isclose == 0) //默认清理
347 {
348 CloseCon(); //热行清理
349 }
350 }
351
352 return true;
353
354 }
355 #endregion
356
357 " getdt 从SQL语句或存储过程中返回DataTable "#region " getdt 从SQL语句或存储过程中返回DataTable "
358 /**//// <summary>
359 /// 返回SQLS中的dt
360 /// </summary>
361 /// <param name="sqlsPro">SQL语句</param>
362 /// <param name="parames">SQL语句参数</param>
363 /// <param name="sid">识别码,0为SQL语句,1为存储过程</param>
364 /// <returns>DateTable</returns>
365 public DataTable getdt(string sqlsPro, DbParameter[] parames, int sid)
366 {
367 DataTable dt = new DataTable();
368 DbDataReader dr = null;
369
370 if (sid == 0) //SQL语句
371 {
372 cmd = ProTxtCmd(sqlsPro, 0);
373 }
374 else //存储过程
375 {
376 cmd = ProTxtCmd(sqlsPro, 1);
377 }
378
379 if (parames != null && parames.Length > 0)
380 {
381 foreach (DbParameter param in parames)
382 if (param.Value != null)
383 cmd.Parameters.Add(param);
384 }
385
386 try
387 {
388 if (cmd.Connection.State != ConnectionState.Open)
389 {
390 cmd.Connection.Open();
391 }
392 dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
393 if (dr.HasRows)
394 {
395 dt.Load(dr);
396 dr.Close();
397 dr = null;
398 }
399 }
400 catch (DbException ex)
401 {
402 dr.Close();
403 dr = null;
404 printEx(ex, 1);
405 }
406 finally
407 {
408 if (this.isclose == 0) //默认清理
409 {
410 if (parames != null)
411 {
412 RemoveParams(cmd);
413 cmd.Parameters.Clear();
414 }
415 CloseCon(); //热行清理
416 }
417 }
418 return dt;
419 }
420 #endregion
421
422 " runsql 执行SQL语句 "#region " runsql 执行SQL语句 "
423 /**//// <summary>
424 /// 运行SQL语句
425 /// </summary>
426 /// <param name="sqlsPro">sql语句</param>
427 /// <param name="parames">SQL语句参数</param>
428 /// <param name="sid">识别ID</param>
429 /// <returns>int</returns>
430 public int runsql(string sqlsPro, DbParameter[] parames, int sid)
431 {
432 int rsInt = 0;
433
434 cmd = null;
435
436 if (sid == 0) //SQL语句
437 {
438 cmd = ProTxtCmd(sqlsPro, 0);
439 }
440 else //存储过程
441 {
442 cmd = ProTxtCmd(sqlsPro, 1);
443 }
444
445 if (parames != null && parames.Length > 0)
446 {
447 foreach (DbParameter param in parames)
448 if (param.Value != null)
449 cmd.Parameters.Add(param);
450 }
451
452 try
453 {
454 if (cmd.Connection.State != ConnectionState.Open)
455 {
456 cmd.Connection.Open();
457 }
458
459 rsInt = cmd.ExecuteNonQuery();
460 }
461 catch (DbException ex)
462 {
463 printEx(ex, 1);
464 }
465 finally
466 {
467 if (this.isclose == 0) //默认清理
468 {
469 if (parames != null)
470 {
471 RemoveParams(cmd);
472 cmd.Parameters.Clear();
473 }
474 CloseCon(); //热行清理
475 }
476 }
477
478 return rsInt;
479
480 }
481 #endregion
482
483 " getSca 泛型,取得单个数据ExecuteScalar,适用于SQL语句及存储过程 "#region " getSca 泛型,取得单个数据ExecuteScalar,适用于SQL语句及存储过程 "
484 /**//// <summary>
485 /// 取得单个数据 (注意如果取整型数据请使用long代替T)
486 /// </summary>
487 /// <typeparam name="T">泛型所替换的数据类型</typeparam>
488 /// <param name="sqlsPro">sql语句</param>
489 /// <param name="parames">SQL语句的参数</param>
490 /// <param name="sid">识别ID,0为SQL语句,1为存储过程</param>
491 /// <returns></returns>
492 public T getSca<T>(string sqlsPro, DbParameter[] parames, int sid)
493 {
494 cmd = null;
495
496 if (sid == 0) //SQL语句
497 {
498 cmd = ProTxtCmd(sqlsPro, 0);
499 }
500 else //存储过程
501 {
502 cmd = ProTxtCmd(sqlsPro, 1);
503 }
504
505 if (parames != null && parames.Length > 0)
506 {
507 foreach (DbParameter param in parames)
508 if (param.Value != null)
509 cmd.Parameters.Add(param);
510 }
511 T Tstr = default(T); /**////泛型变量
512 try
513 {
514 if (cmd.Connection.State != ConnectionState.Open)
515 {
516 cmd.Connection.Open();
517 }
518
519 if (System.DBNull.Value != cmd.ExecuteScalar())
520 {
521 Tstr = (T)cmd.ExecuteScalar(); /**////读取第一行第一列
522 }
523
524 }
525 catch (DbException ex)
526 {
527 printEx(ex, 0);
528 return default(T);
529 }
530 finally
531 {
532 if (this.isclose == 0) //默认清理
533 {
534 if (parames != null)
535 {
536 RemoveParams(cmd);
537 cmd.Parameters.Clear();
538 }
539 CloseCon(); //热行清理
540 }
541 }
542
543 return Tstr;
544
545 }
546 #endregion
547
548 " 使用Adapter填充DataTable "#region " 使用Adapter填充DataTable "
549 /**//// <summary>
550 /// 返回SQLS中的dt
551 /// </summary>
552 /// <param name="sqlsPro">SQL语句</param>
553 /// <param name="parames">SQL语句参数</param>
554 /// <param name="sid">识别码,0为SQL语句,1为存储过程</param>
555 /// <returns>DateTable</returns>
556 public DataTable getAdpdt(string sqlsPro, DbParameter[] parames, Byte sid)
557 {
558 DbProviderFactory dbfactory = getFace(); //取得数据库工厂对像
559
560 adp = dbfactory.CreateDataAdapter();
561
562 if (sid == 0) //SQL语句
563 {
564 cmd = ProTxtCmd(sqlsPro, 0);
565 }
566 else //存储过程
567 {
568 cmd = ProTxtCmd(sqlsPro, 1);
569 }
570
571 if (parames != null && parames.Length > 0)
572 {
573 foreach (DbParameter param in parames)
574 if (param.Value != null)
575 cmd.Parameters.Add(param);
576 }
577
578 adp.SelectCommand = cmd;
579 DataTable dt = new DataTable();
580 try
581 {
582 adp.Fill(dt);
583 }
584 catch (DbException ex)
585 {
586 printEx(ex, 1);
587 }
588 finally
589 {
590 if (this.isclose == 0) //默认清理
591 {
592 if (parames != null)
593 {
594 RemoveParams(cmd);
595 cmd.Parameters.Clear();
596 }
597
598 CloseCon(); //热行清理
599 }
600 }
601 return dt;
602 }
603 #endregion
604
605 " Pagination_dt 分页,适用于SQL SERVER数据库 "#region " Pagination_dt 分页,适用于SQL SERVER数据库 "
606 /**//// <summary>
607 /// 分页函数,返回dt
608 /// </summary>
609 /// <param name="table_name">需要分页显示的表名</param>
610 /// <param name="key">表的主键,必须唯一性</param>
611 /// <param name="orderstr">排序字段如f_Name asc或f_name desc(注意只能有一个排序字段)</param>
612 /// <param name="cpage">当前页</param>
613 /// <param name="psize">每页大小</param>
614 /// <param name="fieles">显示的字段列表</param>
615 /// <param name="filter">条件语句,不加where</param>
616 /// <param name="g_str">分组字段</param> 以前都不再使用
617 /// <param name="pro_name">存储过程名</param>
618 /// <returns>返回内存表</returns>
619 public DataTable Pagination_dt(string table_name, string key, string orderstr, int cpage, int psize, string fieles, string filter, string g_str, string pro_name)
620 {
621
622 DataTable dt = new DataTable();
623
624 SqlCommand cmd = (SqlCommand)ProTxtCmd(pro_name, 1);
625
626 SqlParameter[] parames = { new SqlParameter("@Tables", SqlDbType.VarChar, 50), new SqlParameter("@PrimaryKey", SqlDbType.VarChar, 10), new SqlParameter("@Sort", SqlDbType.VarChar, 50), new SqlParameter("@CurrentPage", SqlDbType.Int, 4), new SqlParameter("@PageSize", SqlDbType.Int, 4), new SqlParameter("@fields", SqlDbType.VarChar, 1000), new SqlParameter("@Filter", SqlDbType.VarChar, 1000), new SqlParameter("@Group", SqlDbType.VarChar, 1000) };
627
628 parames[0].Value = table_name;
629 parames[1].Value = key;
630 parames[2].Value = orderstr;
631 parames[3].Value = cpage;
632 parames[4].Value = psize;
633 parames[5].Value = fieles;
634 parames[6].Value = filter;
635 parames[7].Value = g_str;
636
637 foreach (SqlParameter parameter in parames) /**////添加输入参数集合
638 {
639 cmd.Parameters.Add(parameter);
640 }
641
642 SqlParameter s1 = cmd.Parameters.Add(new SqlParameter("@TotalPage", SqlDbType.Int));
643 SqlParameter s2 = cmd.Parameters.Add(new SqlParameter("@TotalRecord", SqlDbType.Int)); /**////返回值
644 s1.Direction = ParameterDirection.Output;
645 s2.Direction = ParameterDirection.Output;
646
647 DbDataReader dr = null;
648
649 try
650 {
651 if (cmd.Connection.State != ConnectionState.Open)
652 {
653 cmd.Connection.Open();
654 }
655
656 dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); //关闭数据库
657 if (dr.HasRows)
658 {
659 dt.Load(dr);
660 dr.Close();
661 dr.Dispose();
662
663 if (cmd.Parameters["@TotalRecord"].Value != System.DBNull.Value)
664 {
665 allrecord = int.Parse(cmd.Parameters["@TotalRecord"].Value.ToString()); /**////返回总记录数
666 }
667
668
669 if (cmd.Parameters["@TotalPage"].Value != System.DBNull.Value)
670 {
671 allpage = int.Parse(cmd.Parameters["@TotalPage"].Value.ToString()); /**////返回首页数
672 }
673 }
674 }
675 catch (DbException ex)
676 {
677 dr.Close();
678 dr = null;
679 printEx(ex, 1);
680 }
681 finally
682 {
683 if (parames != null)
684 {
685 RemoveParams(cmd);
686 cmd.Parameters.Clear();
687 }
688 CloseCon(); //热行清理
689 }
690
691 return dt;
692 }
693 #endregion
694
695 " Access_dt 分页,适用于ACCESS及其其它使用SQL语句的分页 "#region " Access_dt 分页,适用于ACCESS及其其它使用SQL语句的分页 "
696 /**//// <summary>
697 /// SQL语句分页函数,返回dt
698 /// </summary>
699 /// <param name="table_name">需要分页显示的表名</param>
700 /// <param name="key">表的主键ID,且只能为ID必须唯一性</param>
701 /// <param name="orderstr">排序字段如id ASC,addTimes DESC或id DESC,addTimes ASC(可以有多个排序字段)</param>
702 /// <param name="cpage">当前页</param>
703 /// <param name="psize">每页大小</param>
704 /// <param name="fieles">显示的字段列表</param>
705 /// <param name="filter">条件语句,不加where</param>
706 /// <param name="isDesc">排序方式[true=desc倒序|false=asc顺序]</param>
707 /// <param name="allrecordsqls">客户端传来的计算总记录的SQL语句</param>
708 /// <param name="sql">客户端发来的分页SQL语句</param>
709 /// <returns>返回内存表</returns>
710 public DataTable Access_dt(string table_name, string key, string orderstr, int cpage, int psize, string fieles, string filter, bool isDesc, string allrecordsqls, string sql)
711 {
712 //先计算总记录,再计算总页数
713 string allCordSql = null;
714 if (filter == null) //不存在WHERE子句
715 {
716 allCordSql = "SELECT COUNT(" + key + ") FROM " + table_name + "";
717 }
718 else
719 {
720 allCordSql = "SELECT COUNT(" + key + ") FROM " + table_name + " WHERE " + filter + "";
721 }
722
723 if (allrecordsqls == null)
724 {
725 allrecord = getSca<int>(allCordSql, null, 0); /**////返回总记录数
726 }
727 else
728 {
729 allrecord = getSca<int>(allrecordsqls, null, 0); /**////返回总记录数
730 }
731
732 if (allrecord % psize == 0)
733 {
734 allpage = allrecord / psize; //返回总页数
735 }
736 else
737 {
738 allpage = allrecord / psize + 1; //返回总页数
739 }
740
741 string sqls = null;
742
743 if (isDesc) //倒序[从大到小]
744 {
745 if (filter == null) //不存在WHERE子句
746 {
747 if (cpage == 1)
748 {
749 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " ORDER BY " + orderstr + ""; //第一页
750 }
751 else
752 {
753 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + key + "<(SELECT MIN(" + key + ") FROM (SELECT TOP " + (cpage - 1) * psize + " " + key + " FROM " + table_name + " ORDER BY " + orderstr + ") as T) ORDER BY " + orderstr + ""; //非第一页
754 }
755 }
756 else
757 {
758 if (cpage == 1)
759 {
760 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + filter + " ORDER BY " + orderstr + ""; //第一页
761 }
762 else
763 {
764 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + filter + " AND " + key + "<(SELECT MIN(" + key + ") FROM (SELECT TOP " + (cpage - 1) * psize + " " + key + " FROM " + table_name + " WHERE " + filter + " ORDER BY " + orderstr + ") as T) ORDER BY " + orderstr + ""; //非第一页
765 }
766 }
767 }
768 else //顺序[从小到大]
769 {
770 if (filter == null) //不存在WHERE子句
771 {
772 if (cpage == 1)
773 {
774 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " ORDER BY " + orderstr + ""; //第一页
775 }
776 else
777 {
778 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + key + ">(SELECT MAX(" + key + ") FROM (SELECT TOP " + (cpage - 1) * psize + " " + key + " FROM " + table_name + " ORDER BY " + orderstr + ") as T) ORDER BY " + orderstr + ""; //非第一页
779 }
780 }
781 else
782 {
783 if (cpage == 1)
784 {
785 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + filter + " ORDER BY " + orderstr + ""; //第一页
786 }
787 else
788 {
789 sqls = "SELECT TOP " + psize + " " + fieles + " FROM " + table_name + " WHERE " + filter + " AND " + key + ">(SELECT MAX(" + key + ") FROM (SELECT TOP " + (cpage - 1) * psize + " " + key + " FROM " + table_name + " WHERE " + filter + " ORDER BY " + orderstr + ") as T) ORDER BY " + orderstr + ""; //非第一页
790 }
791 }
792 }
793 //到此构造分页语句完成
794
795 DataTable dt = new DataTable();
796
797 if (sql == null) //客户端没有传入SQL语句
798 {
799 dt = this.getdt(sqls.ToString(), null, 0);
800 }
801 else //有传入
802 {
803 dt = this.getdt(sql, null, 0);
804 }
805
806 return dt;
807
808 }
809 #endregion
810
811 " SQLite分页,只适用于SQLite数据库"#region " SQLite分页,只适用于SQLite数据库"
812 /**//// <param name="tablename">需要分页显示的表名</param>
813 /// <param name="key">表的主键ID,且只能为ID必须唯一性</param>
814 /// <param name="orderstr">排序字段如id ASC,addTimes DESC或id DESC,addTimes ASC(可以有多个排序字段)</param>
815 /// <param name="cpage">当前页</param>
816 /// <param name="psize">每页大小</param>
817 /// <param name="fieles">显示的字段列表</param>
818 /// <param name="filter">条件语句,不加where</param>
819 /// <param name="allrecordsqls">客户端传来的计算总记录的SQL语句</param>
820 /// <param name="sql">客户端发来的分页SQL语句</param>
821 /// <returns>返回内存表</returns>
822 public DataTable SQLite_dt(string tablename, string key, string orderstr, int cpage, int psize, string fieles, string filter, string allrecordsqls, string sql)
823 {
824 //先计算总记录,再计算总页数
825 string allCordSql = null;
826 if (filter == null) //不存在WHERE子句
827 {
828 allCordSql = "SELECT COUNT([" + key + "]) FROM [" + tablename + "]";
829 }
830 else
831 {
832 allCordSql = "SELECT COUNT([" + key + "]) FROM [" + tablename + "] WHERE " + filter + "";
833 }
834
835 if (allrecordsqls == null)
836 {
837 allrecord = int.Parse(this.getSca<long>(allCordSql, null, 0).ToString()); /**////返回总记录数
838 }
839 else
840 {
841 allrecord = int.Parse(this.getSca<long>(allrecordsqls, null, 0).ToString()); /**////返回总记录数
842 }
843
844 if (allrecord % psize == 0)
845 {
846 allpage = allrecord / psize; //返回总页数
847 }
848 else
849 {
850 allpage = allrecord / psize + 1; //返回总页数
851 }
852
853 StringBuilder sqls = new StringBuilder("SELECT " + fieles + " FROM [" + tablename + "]");
854
855 if (filter != null) //不存在WHERE子句
856 {
857 sqls.Append(" WHERE " + filter + " "); //非第一页
858 }
859
860 if (cpage == 1)
861 {
862 sqls.Append(" ORDER BY " + orderstr + " LIMIT " + psize); //第一页
863 }
864 else
865 {
866 sqls.Append(" ORDER BY " + orderstr + " LIMIT " + (psize * cpage - psize) + "," + psize + ""); //非第一页
867 }
868
869 //到此构造分页语句完成 throw new Exception("出现异常:" + sqls.ToString());
870
871 DataTable dt = new DataTable();
872
873 if (sql == null) //客户端没有传入SQL语句
874 {
875 dt = this.getdt(sqls.ToString(), null, 0);
876 }
877 else //有传入
878 {
879 dt = this.getdt(sql, null, 0);
880 }
881
882 return dt;
883 }
884 #endregion
885
886 " IDisposable 成员 "#region " IDisposable 成员 "
887 /**//// <summary>
888 /// 强迫释放数据库连接
889 /// </summary>
890 public void Dispose()
891 {
892 Dispose(true);
893 }
894
895 /**//// <summary>
896 /// 类回收时,关闭数据库连接
897 /// </summary>
898 /// <param name="disposing"></param>
899 public void Dispose(bool disposing)
900 {
901 if (disposing)
902 {
903 CloseCon();
904 }
905 else
906 {
907 CloseCon();
908 }
909 }
910
911 #endregion
912
913 " showpage 显示分页数 "#region " showpage 显示分页数 "
914 /**//// <summary>
915 /// url调整
916 /// </summary>
917 /// <param name="str">网址</param>
918 /// <returns>string</returns>
919 public string joinchar(string str)
920 {
921 if (str == "")
922 {
923 return "";
924 }
925
926 if (str.IndexOf("?") < str.Length)
927 {
928 if (str.IndexOf("?") > 1)
929 {
930 if (str.IndexOf("&") < str.Length)
931 {
932 return str + "&";
933 }
934 else
935 {
936 return str;
937 }
938 }
939 else
940 {
941 return str + "?";
942 }
943 }
944
945 return str;
946 }
947
948 /**//// <summary>
949 /// 显示分页数
950 /// </summary>
951 /// <param name="total">记录数</param>
952 /// <param name="pagenum">每页个数</param>
953 /// <param name="current">当前页</param>
954 /// <param name="url">页面url</param>
955 /// <param name="unit">单位[条|个|位]</param>
956 /// <returns>string</returns>
957 public string showpage(int total, int pagenum, int current, string url, string unit)
958 {
959 StringBuilder str = new StringBuilder();
960 StringBuilder str1 = new StringBuilder();
961
962 int page = 1;
963 if (total % pagenum == 0)
964 {
965 page = total / pagenum;
966 }
967 else
968 {
969 page = total / pagenum + 1;
970 }
971 url = joinchar(url);
972
973 if (page > 10)
974 {
975 if (current <= 5)
976 {
977 for (int i = 1; i <= 9; i++)
978 {
979 if (i == current)
980 {
981 str.Append(" <b>[" + i + "]</b> ");
982 }
983 else
984 {
985 str.Append(" <a href='" + url + "page=" + i + "'>" + i + "</a> ");
986 }
987 }
988 str.Append("" + " <a href='" + url + "page=" + page + "'>" + page + "</a> ");
989 }
990 else if (current >= page - 4)
991 {
992 str.Append(" <a href='" + url + "page=1'>1</a> ");
993 for (int i = page - 8; i <= page; i++)
994 {
995 if (i == current)
996 {
997 str.Append(" <b>[" + i + "]</b> ");
998 }
999 else
1000 {
1001 str.Append(" <a href='" + url + "page=" + i + "'>" + i + "</a> ");
1002 }
1003 }
1004 }
1005 else
1006 {
1007 str.Append(" <a href='" + url + "page=1'>1</a> ");
1008 for (int i = current - 4; i <= current + 4; i++)
1009 {
1010 if (i == current)
1011 {
1012 str.Append(" <b>[" + i + "]</b> ");
1013 }
1014 else
1015 {
1016 str.Append(" <a href='" + url + "page=" + i + "'>" + i + "</a> ");
1017 }
1018 }
1019 str.Append("" + " <a href='" + url + "page=" + page + "'>" + page + "</a> ");
1020 }
1021 }
1022 else
1023 {
1024 for (int i = 1; i <= page; i++)
1025 {
1026 if (page != 1)
1027 {
1028 if (i == current)
1029 {
1030 str.Append(" <b>[" + i + "]</b> ");
1031 }
1032 else
1033 {
1034 str.Append(" <a href='" + url + "page=" + i + "'>" + i + "</a> ");
1035 }
1036 }
1037 }
1038 }
1039 int down = current + 1;
1040 int up = current - 1;
1041 if (page > 1)
1042 {
1043 if (current == 1)
1044 {
1045 str1.Append(" <a href='" + url + "page=2'>下一页</a>");
1046 }
1047 else if (current == page)
1048 {
1049 str1.Append(" <a href='" + url + "page=" + up.ToString() + "'>上一页</a>");
1050 }
1051 else
1052 {
1053 str1.Append(" <a href='" + url + "page=" + up.ToString() + "'>上一页</a> <a href='" + url + "page=" + down.ToString() + "'>下一页</a>");
1054 }
1055 }
1056 if (page == 0) { page = 1; }
1057
1058 return "页次:" + pagenum + "/" + current + "/" + page.ToString() + ",共<span id='rs_count'>" + total.ToString() + "</span>" + unit + " " + str1.ToString() + str.ToString();
1059 }
1060 #endregion
1061
1062 "printEx 打印异常"#region "printEx 打印异常"
1063 /**//// <summary>
1064 /// 打印异常
1065 /// </summary>
1066 /// <param name="ex">异常集合</param>
1067 /// <param name="id">是否显示错误</param>
1068 private void printEx(DbException e, int id)
1069 {
1070 if (this.isclose == 1) //如果isclose的值是1说明没有执行清理工作,所以在异常收集函数里面执行清理工作
1071 {
1072 CloseCon(); //热行清理
1073 }
1074 if (id == 1)
1075 {
1076 string errstr = "错误如下:<br />" + "出错信息:" + e.Message + "<br />" + "出错来源:" + e.Source + "<br />" + "程序:" + e.ErrorCode + "<br />异常方法:" + e.TargetSite;
1077 throw new Exception("出现异常:" + errstr);
1078 }
1079 }
1080 #endregion
1081
1082 }
1083 #endregion
1084
1085}
1086#endregion