BaseDALSQL.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. using Microsoft.Practices.EnterpriseLibrary.Data;
  2. using ProjectBase.Data.Logs;
  3. using ProjectBase.Data.Pager;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using System.Data.Common;
  9. using System.Data.SqlClient;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace ProjectBase.Data.BaseDAL.BaseDatabase
  14. {
  15. /// <summary>
  16. /// 数据访问层的基类
  17. /// </summary>
  18. public abstract class BaseDALSQL<T> : AbstractBaseDAL<T>, IBaseDAL<T> where T : BaseEntity, new()
  19. {
  20. #region 构造函数
  21. /// <summary>
  22. /// 默认构造函数
  23. /// </summary>
  24. public BaseDALSQL()
  25. { }
  26. /// <summary>
  27. /// 指定表名以及主键,对基类进构造
  28. /// </summary>
  29. /// <param name="tableName">表名</param>
  30. /// <param name="primaryKey">表主键</param>
  31. public BaseDALSQL(string tableName, string primaryKey)
  32. : base(tableName, primaryKey)
  33. {
  34. base.parameterPrefix = "@"; //数据库参数化访问的占位符
  35. base.safeFieldFormat = "[{0}]"; //防止和保留字、关键字同名的字段格式,如[value]
  36. }
  37. #endregion
  38. #region 通用操作方法
  39. /// <summary>
  40. /// 添加记录
  41. /// </summary>
  42. /// <param name="recordField">Hashtable:键[key]为字段名;值[value]为字段对应的值</param>
  43. /// <param name="targetTable">需要操作的目标表名称</param>
  44. /// <param name="trans">事务对象,如果使用事务,传入事务对象,否则为Null不使用事务</param>
  45. public override int Insert2(Hashtable recordField, string targetTable, DbTransaction trans)
  46. {
  47. int result = -1;
  48. string fields = ""; // 字段名
  49. string vals = ""; // 字段值
  50. if (recordField == null || recordField.Count < 1)
  51. {
  52. return result;
  53. }
  54. SqlParameter[] param = new SqlParameter[recordField.Count];
  55. IEnumerator eKeys = recordField.Keys.GetEnumerator();
  56. int i = 0;
  57. while (eKeys.MoveNext())
  58. {
  59. string field = eKeys.Current.ToString();
  60. fields += field + ",";
  61. vals += string.Format("@{0},", field);
  62. object val = recordField[eKeys.Current.ToString()];
  63. param[i] = new SqlParameter("@" + field, val);
  64. i++;
  65. }
  66. fields = fields.Trim(',');//除去前后的逗号
  67. vals = vals.Trim(',');//除去前后的逗号
  68. string sql = string.Format("INSERT INTO {0} ({1}) VALUES ({2});SELECT SCOPE_IDENTITY()", targetTable, fields, vals);
  69. Database db = CreateDatabase();
  70. DbCommand command = db.GetSqlStringCommand(sql);
  71. foreach (string field in recordField.Keys)
  72. {
  73. object val = recordField[field];
  74. val = val ?? DBNull.Value;
  75. if (val is DateTime)
  76. {
  77. if (Convert.ToDateTime(val) <= Convert.ToDateTime("1753-1-1"))
  78. {
  79. val = DBNull.Value;
  80. }
  81. }
  82. db.AddInParameter(command, field, TypeToDbType(val.GetType()), val);
  83. }
  84. if (trans != null)
  85. {
  86. result = Convert.ToInt32(db.ExecuteScalar(command, trans).ToString());
  87. }
  88. else
  89. {
  90. result = Convert.ToInt32(db.ExecuteScalar(command).ToString());
  91. }
  92. return result;
  93. }
  94. /// <summary>
  95. /// 测试数据库是否正常连接
  96. /// </summary>
  97. public override bool TestConnection(string connectionString)
  98. {
  99. bool result = false;
  100. using (DbConnection connection = new SqlConnection(connectionString))
  101. {
  102. connection.Open();
  103. if (connection.State == System.Data.ConnectionState.Open)
  104. {
  105. result = true;
  106. }
  107. }
  108. return result;
  109. }
  110. #endregion
  111. #region 对象添加、修改、查询接口
  112. /// <summary>
  113. /// 查找记录表中最旧的一条记录
  114. /// </summary>
  115. /// <param name="trans">事务对象</param>
  116. /// <returns></returns>
  117. public override T FindFirst(DbTransaction trans = null)
  118. {
  119. string sql = string.Format("Select top 1 {0} From {1} Order by {2} ASC", selectedFields, tableName, GetSafeFileName(sortField));
  120. Database db = CreateDatabase();
  121. DbCommand command = db.GetSqlStringCommand(sql);
  122. T entity = GetEntity(db, command, trans);
  123. return entity;
  124. }
  125. /// <summary>
  126. /// 查找记录表中最新的一条记录
  127. /// </summary>
  128. /// <param name="trans">事务对象</param>
  129. /// <returns></returns>
  130. public override T FindLast(DbTransaction trans = null)
  131. {
  132. string sql = string.Format("Select top 1 {0} From {1} Order by {2} DESC", selectedFields, tableName, GetSafeFileName(sortField));
  133. Database db = CreateDatabase();
  134. DbCommand command = db.GetSqlStringCommand(sql);
  135. T entity = GetEntity(db, command, trans);
  136. return entity;
  137. }
  138. #region 下面两个覆盖基类函数,指定具体的数据库类型
  139. /// <summary>
  140. /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
  141. /// </summary>
  142. /// <param name="condition">查询的条件</param>
  143. /// <param name="info">分页实体</param>
  144. /// <param name="fieldToSort">排序字段</param>
  145. /// <param name="desc">是否降序</param>
  146. /// <param name="trans">事务对象</param>
  147. /// <returns>指定对象的集合</returns>
  148. public override List<T> FindWithPager(string condition, PagerInfo info, string fieldToSort, bool desc, DbTransaction trans = null)
  149. {
  150. if (HasInjectionData(condition))
  151. {
  152. LogHelper.log.Error(string.Format("检测出SQL注入的恶意数据, {0}", condition));
  153. throw new Exception("检测出SQL注入的恶意数据");
  154. }
  155. PagerHelper helper = new PagerHelper(tableName, this.selectedFields, fieldToSort,
  156. info.PageSize, info.CurrenetPageIndex, desc, condition);
  157. string countSql = helper.GetPagingSql(DatabaseType.SqlServer, true);
  158. string strCount = SqlValueList(countSql, trans);
  159. info.RecordCount = Convert.ToInt32(strCount);
  160. string dataSql = helper.GetPagingSql(DatabaseType.SqlServer, false);
  161. List<T> list = GetList(dataSql, null, trans);
  162. return list;
  163. }
  164. /// <summary>
  165. /// 根据条件查询数据库,并返回DataTable集合(用于分页数据显示)
  166. /// </summary>
  167. /// <param name="condition">查询的条件</param>
  168. /// <param name="info">分页实体</param>
  169. /// <param name="fieldToSort">排序字段</param>
  170. /// <param name="desc">是否降序</param>
  171. /// <param name="trans">事务对象</param>
  172. /// <returns>指定DataTable的集合</returns>
  173. public override DataTable FindToDataTable(string condition, PagerInfo info, string fieldToSort, bool desc, DbTransaction trans = null)
  174. {
  175. if (HasInjectionData(condition))
  176. {
  177. LogHelper.log.Error(string.Format("检测出SQL注入的恶意数据, {0}", condition));
  178. throw new Exception("检测出SQL注入的恶意数据");
  179. }
  180. PagerHelper helper = new PagerHelper(tableName, this.selectedFields, fieldToSort,
  181. info.PageSize, info.CurrenetPageIndex, desc, condition);
  182. string countSql = helper.GetPagingSql(DatabaseType.SqlServer, true);
  183. string strCount = SqlValueList(countSql, trans);
  184. info.RecordCount = Convert.ToInt32(strCount);
  185. string dataSql = helper.GetPagingSql(DatabaseType.SqlServer, false);
  186. return GetDataTableBySql(dataSql, trans);
  187. }
  188. #endregion
  189. /// <summary>
  190. /// 获取前面记录指定数量的记录
  191. /// </summary>
  192. /// <param name="sql">查询语句</param>
  193. /// <param name="count">指定数量</param>
  194. /// <param name="orderBy">排序条件,例如order by id</param>
  195. /// <param name="trans">事务对象</param>
  196. /// <returns></returns>
  197. public override DataTable GetTopResult(string sql, int count, string orderBy, DbTransaction trans = null)
  198. {
  199. string resultSql = string.Format("select top {0} * from ({1} {2}) ", count, sql, orderBy);
  200. return SqlTable(resultSql, trans);
  201. }
  202. #endregion
  203. #region 特殊的操作
  204. /// <summary>
  205. /// 兼容Oracle的字段大写的重写函数
  206. /// </summary>
  207. /// <param name="sql">sql语句</param>
  208. /// <param name="trans">事务对象</param>
  209. /// <returns></returns>
  210. public override DataTable SqlTable(string sql, DbTransaction trans = null)
  211. {
  212. return base.SqlTable(sql.ToUpper(), trans);
  213. }
  214. /// <summary>
  215. /// 兼容Oracle的字段大写的重写函数
  216. /// </summary>
  217. /// <param name="sql">sql语句</param>
  218. /// <param name="parameters">SQL参数集合</param>
  219. /// <param name="trans">事务对象</param>
  220. /// <returns></returns>
  221. public override DataTable SqlTable(string sql, DbParameter[] parameters, DbTransaction trans = null)
  222. {
  223. return base.SqlTable(sql.ToUpper(), parameters, trans);
  224. }
  225. /// <summary>
  226. /// 获取数据库的全部表名称
  227. /// </summary>
  228. /// <returns></returns>
  229. public override List<string> GetTableNames()
  230. {
  231. string sql = string.Format("SELECT name FROM sysobjects WHERE (xtype = 'U') order by name");
  232. Database db = CreateDatabase();
  233. DbCommand command = db.GetSqlStringCommand(sql);
  234. List<string> list = new List<string>();
  235. using (IDataReader dr = db.ExecuteReader(command))
  236. {
  237. while (dr.Read())
  238. {
  239. list.Add(dr[0].ToString());
  240. }
  241. }
  242. return list;
  243. }
  244. #endregion
  245. }
  246. }