当前位置:Gxlcms > 数据库问题 > C# .NET数据库操作

C# .NET数据库操作

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

  1. DbHelper helper = new DbHelper();
  2. helper.createConnection("MyConnection","Data Source=CN-20161106HMJI;Initial Catalog=ShopInfo;Integrated Security=True",DbType.SQL);
  3. PlaceInfo model = helper.ExcuteString(o => o.From("PlaceInfo").Select().AndWhere("SAddNo", 1)).ToModel<PlaceInfo>();
  4. Console.Read();
技术分享

  上面是使用的一个例子,创建连接字符串,然后查询获取实例,已经没有打开数据库,或者是command的语句,使用起来是否十分简单,上面这句运行没有问题的,因为框架灵活度太大,测试的话不能所有都包含,这也是没办法,接下来跟着文章,一步步分析。

  上次说,链式编程很好用,所以这次同样是链式编程,但这次更为强大。大家知道,dal的链式编程,主要是得到数据,而得到数据无非是对数据库查询语言进行封装。所以,在框架上,我封装了一个拼接语句的类,里面包含了我认为比较常用的数据库语句,支持order by。还有最强大的是,能够支持嵌套查询!也就是封装的sql语句可以是

select * from tableName where Id in(select id from tablename where ...)...这样子的。使用起来十分的方便。而且还有排序order by,等,可以在使用这套框架封装更使用的方法。

  第二个新增的是连接控制,这个是这套框架的关键,因为框架不能占用内存,所以无论在拼接查询语句,还是在执行部分,都没有对数据库创建的语句,而是采用注入式,通过连接控制类,创建好数据库连接后,注入到所需要的部分中。而且这里控制了最耗性能的反射,对模型中的属性进行反射,都是耗时间,所以这里设置了缓存,对已经创建过对象的保存在这里,在拼接数据库语句或者是执行阶段需要用到,注入到其中,就可以省下时间。

  第三个增加的是异常类,不过我封装的比较简单,里面就一个可重载的方法,这个是用来发生异常时候,用户能够自己设置发生错误之后应该做什么(比如保存到日志)而定的。

  最后一个新增的是释放资源,因为对数据库连接,数据库连接数目比较少,但是command的数目在一般项目可就不是这样。可能大家为了方便,所以使用的时候尽情的new这样,那在我的框架设置了一个集合,专门存放command的,在用完后能够释放资源。因为考虑到在事务执行时候不能够对comand进行释放,所以在释放时候还做了判断。把有事务的command放到在事务执行后释放。

 

  看完上边的功能,是不是觉得十分强大,因为这个框架理解和实现起来都不容易,所以笔者尽可能的让大家明白,知道我是怎么一步步完成的。

  现在进入正题,先看下简单的结构图,看上去比较简单,不是我不会绘图,我在完成其他项目时候,都有完整的文档和图,因为现在没有太多时间,而且用软件画实在太慢了,所以大家将就的看吧。

技术分享

  上图就是我框架的结构图。箭头代表关联,从下到上,代表底层到用户使用的层次。框架是支持对数据库的扩展,上边三个部分写继承抽象类就是如此,因为这几个其实就是实际数据库会使用到,所以使用工厂模式,这样就能够扩展其他了。

  好了,看完图,就开始讲解代码。

  我第一步是从数据库拼接语句开始做的,因为这个虽然还不算底层,但是相对于其他可以独立,那么看下这一跪部分的类:

技术分享
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Dal
  6. {
  7. public interface IDbCode
  8. {
  9. /// <summary>
  10. /// 数据库执行表、视图、存储过程等对象
  11. /// </summary>
  12. /// <param name="Object">名称</param>
  13. /// <returns></returns>
  14. IDbCode From(object Object);
  15. /// <summary>
  16. /// 查询
  17. /// </summary>
  18. /// <param name="Fields">查询的字段</param>
  19. /// <returns></returns>
  20. IDbCode Select(string Fields = "*");
  21. /// <summary>
  22. /// 删除
  23. /// </summary>
  24. /// <returns></returns>
  25. IDbCode Delete();
  26. /// <summary>
  27. /// 更新
  28. /// </summary>
  29. /// <param name="model">更新对象</param>
  30. /// <param name="Fields">更新字段</param>
  31. /// <returns></returns>
  32. IDbCode Update(object model,string Fields = "");
  33. /// <summary>
  34. /// 插入
  35. /// </summary>
  36. /// <param name="model">插入对象</param>
  37. /// <param name="Fields">插入字段</param>
  38. /// <returns></returns>
  39. IDbCode Insert(object model,string Fields = "");
  40. /// <summary>
  41. /// 与条件
  42. /// </summary>
  43. /// <param name="Where">条件字符串</param>
  44. /// <returns></returns>
  45. IDbCode AndWhere(string Where);
  46. /// <summary>
  47. /// 与条件
  48. /// </summary>
  49. /// <param name="Field">字段</param>
  50. /// <param name="Value">值</param>
  51. /// <returns></returns>
  52. IDbCode AndWhere(string Field,object Value);
  53. /// <summary>
  54. /// 与条件
  55. /// </summary>
  56. /// <param name="Field">条件字段</param>
  57. /// <param name="Select">嵌套查询条件委托</param>
  58. /// <returns></returns>
  59. IDbCode AndWhere(string Field, Func<IDbCode, string> Select);
  60. /// <summary>
  61. /// 与条件
  62. /// </summary>
  63. /// <typeparam name="T">值的类型</typeparam>
  64. /// <param name="Field">条件字段</param>
  65. /// <param name="Values">值</param>
  66. /// <returns></returns>
  67. IDbCode AndWhere<T>(string Field,List<T> Values);
  68. /// <summary>
  69. /// 或条件
  70. /// </summary>
  71. /// <param name="Where">条件字符串</param>
  72. /// <returns></returns>
  73. IDbCode OrWhere(string Where);
  74. /// <summary>
  75. /// 或条件
  76. /// </summary>
  77. /// <param name="Field">条件字段</param>
  78. /// <param name="Value">值</param>
  79. /// <returns></returns>
  80. IDbCode OrWhere(string Field, object Value);
  81. /// <summary>
  82. /// 或条件
  83. /// </summary>
  84. /// <param name="Field">条件字段</param>
  85. /// <param name="Select">嵌套条件</param>
  86. /// <returns></returns>
  87. IDbCode OrWhere(string Field, Func<IDbCode, string> Select);
  88. /// <summary>
  89. /// 或条件
  90. /// </summary>
  91. /// <typeparam name="T">值类型</typeparam>
  92. /// <param name="Field">条件字段</param>
  93. /// <param name="Values">值</param>
  94. /// <returns></returns>
  95. IDbCode OrWhere<T>(string Field, List<T> Values);
  96. /// <summary>
  97. /// Top 语句
  98. /// </summary>
  99. /// <param name="topCount"></param>
  100. /// <returns></returns>
  101. IDbCode Top(int topCount);
  102. /// <summary>
  103. /// 排序从小到大
  104. /// </summary>
  105. /// <param name="Field">排序字段</param>
  106. /// <returns></returns>
  107. IDbCode OrderByAsc(string Field);
  108. /// <summary>
  109. /// 排序从大到小
  110. /// </summary>
  111. /// <param name="Field">排序字段</param>
  112. /// <returns></returns>
  113. IDbCode OrderByDesc(string Field);
  114. /// <summary>
  115. /// 多表查询时候必须加的条件
  116. /// </summary>
  117. /// <param name="Fields">在两张表中的相同字段</param>
  118. /// <returns></returns>
  119. IDbCode ForMulTable(string Fields);
  120. string ToString();
  121. /// <summary>
  122. /// 清空缓存
  123. /// </summary>
  124. /// <returns></returns>
  125. IDbCode Clear();
  126. IDbCode CreateCode(string sql);
  127. object Paras
  128. {
  129. get;
  130. }
  131. void Dispose();
  132. }
  133. }
技术分享

继承它的类:

技术分享
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Reflection;
  8. namespace Dal
  9. {
  10. public class SQLCode :IDbCode
  11. {
  12. string Object;
  13. StringBuilder ExcuteString = new StringBuilder();
  14. List<SqlParameter> paras;
  15. Dictionary<string, List<PropertyInfo>> pro;
  16. static string[] s = { "select", "delect", "update", "insert" };
  17. public SQLCode()
  18. {
  19. paras = new List<SqlParameter>();
  20. }
  21. public SQLCode(Dictionary<string, List<PropertyInfo>> pro)
  22. {
  23. paras = new List<SqlParameter>();
  24. this.pro = pro;
  25. }
  26. public SQLCode(List<SqlParameter> paras, Dictionary<string, List<PropertyInfo>> pro)
  27. {
  28. this.paras = paras;
  29. this.pro = pro;
  30. }
  31. public IDbCode From(object Object)
  32. {
  33. Type t = Object.GetType();
  34. if(t.Name.ToLower().Equals("string"))
  35. {
  36. this.Object = Object.ToString();
  37. }else
  38. {
  39. this.Object = t.Name;
  40. }
  41. return this;
  42. }
  43. public IDbCode Select(string Fields = "*")
  44. {
  45. if (this.Object.Length <= 0)
  46. return this;
  47. if (!Check(0))
  48. return this;
  49. ExcuteString.AppendLine("select " + Fields +" from "+ this.Object);
  50. ExcuteString.AppendLine(" where 1 = 1 ");
  51. return this;
  52. }
  53. bool Check(int Type)
  54. {
  55. int flag = 0;
  56. string b = ExcuteString.ToString();
  57. for (int i = 0; i < s.Length; i++)
  58. if(i!=Type)
  59. flag += b.Contains(s[i]) ? 1 : 0;
  60. return flag == 0;
  61. }
  62. public IDbCode Delete()
  63. {
  64. if (Object.Length <= 0)
  65. return this;
  66. if (!Check(1))
  67. return this;
  68. ExcuteString.AppendLine("delete " + this.Object);
  69. ExcuteString.AppendLine(" where 1 = 1 ");
  70. return this;
  71. }
  72. public IDbCode Update(object model, string Fields = "")
  73. {
  74. if (this.Object.Length <= 0)
  75. return this;
  76. if (!Check(2))
  77. return this;
  78. Type t = model.GetType();
  79. if (t.Name != Object)
  80. return this;
  81. ExcuteString.AppendLine("update "+this.Object +" set ");
  82. List<PropertyInfo> p;
  83. if(pro.ContainsKey(t.Name))
  84. {
  85. p = pro[t.Name];
  86. }else
  87. {
  88. p = t.GetProperties().ToList();
  89. pro.Add(t.Name, p);
  90. }
  91. string f = "";
  92. if(Fields.Length==0)
  93. {
  94. p.ForEach(o =>
  95. {
  96. f += o.Name + " = @" + o.Name;
  97. paras.Add(new SqlParameter(o.Name, o.GetValue(model, null)));
  98. });
  99. }else
  100. {
  101. string[] a = Fields.Split(‘,‘);
  102. p.ForEach(o =>
  103. {
  104. if (a.Contains(o.Name))
  105. {
  106. f += o.Name + " = @" + o.Name + ",";
  107. paras.Add(new SqlParameter(o.Name, o.GetValue(model, null)));
  108. }
  109. });
  110. }
  111. ExcuteString.AppendLine(f);
  112. ExcuteString.AppendLine("where 1 = 1");
  113. return this;
  114. }
  115. public IDbCode Insert(object model, string Fields = "")
  116. {
  117. if (this.Object.Length <= 0)
  118. return this;
  119. if (!Check(3))
  120. return this;
  121. Type t = model.GetType();
  122. if (t.Name != Object)
  123. return this;
  124. ExcuteString.AppendLine("insert " + this.Object);
  125. List<PropertyInfo> p;
  126. if (pro.ContainsKey(t.Name))
  127. {
  128. p = pro[t.Name];
  129. }
  130. else
  131. {
  132. p = t.GetProperties().ToList();
  133. pro.Add(t.Name, p);
  134. }
  135. string f = "( ";
  136. string f1 = "values( ";
  137. if (Fields.Length == 0)
  138. {
  139. p.ForEach(o =>
  140. {
  141. f += o.Name+",";
  142. paras.Add(new SqlParameter(o.Name, o.GetValue(model, null)));
  143. f1 += "@" + o.Name + ",";
  144. });
  145. }
  146. else
  147. {
  148. string[] a = Fields.Split(‘,‘);
  149. p.ForEach(o =>
  150. {
  151. if (a.Contains(o.Name))
  152. {
  153. f += o.Name + ",";
  154. paras.Add(new SqlParameter(o.Name, o.GetValue(model, null)));
  155. f1 += "@" + o.Name + ",";
  156. }
  157. });
  158. }
  159. f = f.Remove(f.LastIndexOf(‘,‘), 1) + " ) ";
  160. f1 = f1.Remove(f1.LastIndexOf(‘,‘), 1) + " ) ";
  161. ExcuteString.AppendLine(f);
  162. ExcuteString.AppendLine(f1);
  163. return this;
  164. }
  165. public IDbCode AndWhere(string Where)
  166. {
  167. ExcuteString.AppendLine(" and " + Where);
  168. return this;
  169. }
  170. public IDbCode AndWhere(string Field, object Value)
  171. {
  172. ExcuteString.AppendLine(" and " + Field + " = @" + Field);
  173. paras.Add(new SqlParameter(Field, Value));
  174. return this;
  175. }
  176. public IDbCode AndWhere(string Field, Func<IDbCode, string> Select)
  177. {
  178. ExcuteString.AppendLine(" and " + Field + " in " + Select(new SQLCode(this.paras,this.pro)));
  179. return this;
  180. }
  181. public IDbCode AndWhere<T>(string Field, List<T> Values)
  182. {
  183. string value = "(";
  184. Values.ForEach(o =>
  185. {
  186. value += o + ",";
  187. });
  188. ExcuteString.AppendLine(" and " + Field + " in " + value.Remove(value.LastIndexOf(‘,‘), 1) + ")");
  189. return this;
  190. }
  191. public IDbCode OrWhere(string Where)
  192. {
  193. ExcuteString.AppendLine(" or " + Where);
  194. return this;
  195. }
  196. public IDbCode OrWhere(string Field, object Value)
  197. {
  198. ExcuteString.AppendLine(" or " + Field + " = @" + Field);
  199. paras.Add(new SqlParameter(Field, Value));
  200. return this;
  201. }
  202. public IDbCode OrWhere(string Field, Func<IDbCode, string> Select)
  203. {
  204. ExcuteString.AppendLine(" or " + Field + " in " + Select(new SQLCode(this.paras,this.pro)));
  205. return this;
  206. }
  207. public IDbCode OrWhere<T>(string Field, List<T> Values)
  208. {
  209. string value = "(";
  210. Values.ForEach(o =>
  211. {
  212. value += o + ",";
  213. });
  214. ExcuteString.AppendLine(" or " + Field + " in " + value.Remove(value.LastIndexOf(‘,‘), 1) + ")");
  215. return this;
  216. }
  217. public IDbCode Top(int topCount)
  218. {
  219. if (!ExcuteString.ToString().Contains(s[0]))
  220. return this;
  221. ExcuteString.Replace("select", "select top " + topCount +" ");
  222. return this;
  223. }
  224. bool CheckHasOrderBy()
  225. {
  226. return this.ExcuteString.ToString().Contains("order by");
  227. }
  228. public IDbCode OrderByAsc(string Field)
  229. {
  230. if (CheckHasOrderBy())
  231. ExcuteString.AppendLine("," + Field + " asc");
  232. else
  233. ExcuteString.AppendLine(" order by " + Field+" asc");
  234. return this;
  235. }
  236. public IDbCode OrderByDesc(string Field)
  237. {
  238. if (CheckHasOrderBy())
  239. ExcuteString.AppendLine("," + Field + " desc");
  240. else
  241. ExcuteString.AppendLine(" order by " + Field + " desc");
  242. return this;
  243. }
  244. public IDbCode ForMulTable(string Fields)
  245. {
  246. List<string> tables = this.Object.Split(‘,‘).ToList();
  247. Fields.Split(‘,‘).ToList().ForEach(o =>
  248. {
  249. for (int i = 0; i < tables.Count - 1; i++)
  250. {
  251. ExcuteString.AppendLine(" and " + tables[i] + "." + o + " = " + tables[i + 1] + "." + o);
  252. }
  253. });
  254. return this;
  255. }
  256. public override string ToString()
  257. {
  258. return this.ExcuteString.ToString();
  259. }
  260. public IDbCode Clear()
  261. {
  262. pro.Clear();
  263. return this;
  264. }
  265. public IDbCode CreateCode(string sql)
  266. {
  267. ExcuteString.AppendLine(sql);
  268. return this;
  269. }
  270. public object Paras
  271. {
  272. get
  273. {
  274. return this.paras;
  275. }
  276. }
  277. public void Dispose()
  278. {
  279. this.pro = null;
  280. }
  281. }
  282. }
技术分享

  如果有看过上次的文章,那么就知道这里部分方法用到反射,获取其中的属性来拼写语句。没什么难的,大家看到里面有许多的if条件,是我避免在链式组合时候,用户随便乱时候而设置的。这部分都是对字符串处理。

  第二部分是执行语句,这个相信大家写多了,先给代码:

技术分享
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. namespace Dal
  8. {
  9. public interface IDbExcute
  10. {
  11. T ToModel<T>(IDbCode code, CommandType type = CommandType.Text)
  12. where T : class,new();
  13. List<T> ToList<T>(IDbCode code,CommandType type = CommandType.Text)
  14. where T : class,new();
  15. object ToResult(IDbCode code, CommandType type = CommandType.Text);
  16. int ExcuteResult(IDbCode code, CommandType type = CommandType.Text);
  17. DataTable ToDataTable(IDbCode code, CommandType type = CommandType.Text);
  18. DataSet ToDataSet(IDbCode code, CommandType type = CommandType.Text);
  19. void OpenConnection();
  20. void CloseConnection();
  21. void Dispose(object tran);
  22. void BeginTransation(string Name);
  23. void Commit();
  24. void RollBack();
  25. }
  26. }
技术分享

上面就是支持整个框架的执行方法

技术分享
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Reflection;
  8. namespace Dal
  9. {
  10. public class SQLExcute : IDbExcute
  11. {
  12. SqlConnection conn;
  13. Dictionary<string, List<PropertyInfo>> pro;
  14. Dictionary<string, SqlCommand> command;
  15. SqlTransaction tran = null;
  16. public SQLExcute(SqlConnection conn, Dictionary<string, List<PropertyInfo>> pro)
  17. {
  18. this.conn = conn;
  19. this.pro = pro;
  20. command = new Dictionary<string, SqlCommand>();
  21. }
  22. public List<T> ToList<T>(IDbCode code,CommandType type = CommandType.Text)
  23. where T:class,new()
  24. {
  25. List<T> list = new List<T>();
  26. string name = DateTime.Now.ToString();
  27. command.Add(name, new SqlCommand());
  28. SqlCommand com = command[name];
  29. com.Connection = conn;
  30. com.CommandText = code.ToString();
  31. com.CommandType = type;
  32. setCommand(com, (List<SqlParameter>)code.Paras);
  33. Type t = typeof(T);
  34. List<PropertyInfo> pros;
  35. if(pro.ContainsKey(t.Name))
  36. {
  37. pros = pro[t.Name];
  38. }else
  39. {
  40. pros = t.GetProperties().ToList();
  41. pro.Add(t.Name, pros);
  42. }
  43. try
  44. {
  45. this.OpenConnection();
  46. using (SqlDataReader reader = com.ExecuteReader())
  47. {
  48. while(reader.Read())
  49. {
  50. T model = new T();
  51. pros.ForEach(o =>
  52. {
  53. if(ReaderExists(reader,o.Name))
  54. {
  55. o.SetValue(model, reader[o.Name], null);
  56. }
  57. });
  58. list.Add(model);
  59. }
  60. }
  61. }
  62. catch (Exception ex)
  63. {
  64. throw ex;
  65. }
  66. finally
  67. {
  68. this.Dispose(name);
  69. this.CloseConnection();
  70. }
  71. return list;
  72. }
  73. public bool ReaderExists(SqlDataReader reader, string columnName)
  74. {
  75. //reader.GetSchemaTable().DefaultView.RowFilter = "ColumnName= ‘" + columnName + "‘";
  76. //return (reader.GetSchemaTable().DefaultView.Count > 0);
  77. return reader.GetSchemaTable().Select("ColumnName=‘" + columnName + "‘").Length > 0;
  78. }
  79. public void Dispose(string name)
  80. {
  81. if(command.ContainsKey(name))
  82. {
  83. SqlCommand com = command[name];
  84. command.Remove(name);
  85. com.Dispose();
  86. }
  87. if (command.Count <= 0)
  88. this.CloseConnection();
  89. }
  90. public void Dispose(object tran)
  91. {
  92. List<string> list = command.Keys.ToList();
  93. list.ForEach(o =>
  94. {
  95. if(command[o].Transaction!=null&&command[o].Transaction==(SqlTransaction)tran)
  96. {
  97. this.Dispose(o);
  98. }
  99. });
  100. }
  101. public object ToResult(IDbCode code, CommandType type = CommandType.Text)
  102. {
  103. string name = DateTime.Now.ToString();
  104. command.Add(name, new SqlCommand());
  105. SqlCommand com = command[name];
  106. com.Connection = conn;
  107. com.CommandText = code.ToString();
  108. com.CommandType = type;
  109. setCommand(com, (List<SqlParameter>)code.Paras);
  110. object result =null;
  111. try
  112. {
  113. this.OpenConnection();
  114. result = com.ExecuteScalar();
  115. }
  116. catch (Exception ex)
  117. {
  118. DoException();
  119. throw ex;
  120. }finally
  121. {
  122. this.Dispose(name);
  123. this.CloseConnection();
  124. }
  125. return result;
  126. }
  127. private void DoException()
  128. {
  129. new DbException().Done();
  130. }
  131. public int ExcuteResult(IDbCode code, CommandType type = CommandType.Text)
  132. {
  133. string name = DateTime.Now.ToString();
  134. command.Add(name, new SqlCommand());
  135. SqlCommand com = command[name];
  136. com.Connection = conn;
  137. com.CommandText = code.ToString();
  138. com.CommandType = type;
  139. setCommand(com, (List<SqlParameter>)code.Paras);
  140. int result = 0;
  141. try
  142. {
  143. this.OpenConnection();
  144. if (tran != null)
  145. com.Transaction = (SqlTransaction)tran;
  146. result = com.ExecuteNonQuery();
  147. }
  148. catch (Exception ex)
  149. {
  150. DoException();
  151. throw ex;
  152. }
  153. finally
  154. {
  155. if (tran == null)
  156. Dispose(name);
  157. this.CloseConnection();
  158. }
  159. return result;
  160. }
  161. public System.Data.DataTable ToDataTable(IDbCode code, CommandType type = CommandType.Text)
  162. {
  163. string name = DateTime.Now.ToString();
  164. command.Add(name, new SqlCommand());
  165. SqlCommand com = command[name];
  166. com.Connection = conn;
  167. com.CommandText = code.ToString();
  168. com.CommandType = type;
  169. setCommand(com, (List<SqlParameter>)code.Paras);
  170. DataTable dt = new DataTable();
  171. try
  172. {
  173. using(SqlDataAdapter adapter = new SqlDataAdapter(com))
  174. {
  175. adapter.Fill(dt);
  176. }
  177. }
  178. catch (Exception ex)
  179. {
  180. DoException();
  181. throw ex;
  182. }finally
  183. {
  184. Dispose(name);
  185. }
  186. return dt;
  187. }
  188. public void setCommand(SqlCommand com,List<SqlParameter> paras)
  189. {
  190. paras.ForEach(o =>
  191. {
  192. com.Parameters.Add(o);
  193. });
  194. }
  195. public System.Data.DataSet ToDataSet(IDbCode code, CommandType type = CommandType.Text)
  196. {
  197. string name = DateTime.Now.ToString();
  198. command.Add(name, new SqlCommand());
  199. SqlCommand com = command[name];
  200. com.Connection = conn;
  201. com.CommandText = code.ToString();
  202. com.CommandType = type;
  203. setCommand(com, (List<SqlParameter>)code.Paras);
  204. DataSet dt = new DataSet();
  205. try
  206. {
  207. using (SqlDataAdapter adapter = new SqlDataAdapter(com))
  208. {
  209. adapter.Fill(dt);
  210. }
  211. }
  212. catch (Exception ex)
  213. {
  214. DoException();
  215. throw ex;
  216. }
  217. finally
  218. {
  219. Dispose(name);
  220. }
  221. return dt;
  222. }
  223. public T ToModel<T>(IDbCode code, CommandType type = CommandType.Text)
  224. where T : class,new()
  225. {
  226. string name = DateTime.Now.ToString();
  227. command.Add(name, new SqlCommand());
  228. SqlCommand com = command[name];
  229. com.Connection = conn;
  230. com.CommandText = code.ToString();
  231. com.CommandType = type;
  232. setCommand(com, (List<SqlParameter>)code.Paras);
  233. Type t = typeof(T);
  234. List<PropertyInfo> p = null;
  235. if(pro.ContainsKey(t.Name))
  236. {
  237. p = pro[t.Name];
  238. }else
  239. {
  240. p = t.GetProperties().ToList();
  241. pro.Add(t.Name, p);
  242. }
  243. T model = new T();
  244. try
  245. {
  246. this.OpenConnection();
  247. using(SqlDataReader reader = com.ExecuteReader())
  248. {
  249. if(reader.Read())
  250. {
  251. p.ForEach(o =>
  252. {
  253. if(ReaderExists(reader,o.Name))
  254. {
  255. o.SetValue(model, reader[o.Name], null);
  256. }
  257. });
  258. }
  259. }
  260. }
  261. catch (Exception ex)
  262. {
  263. DoException();
  264. throw ex;
  265. }
  266. finally
  267. {
  268. Dispose(name);
  269. this.CloseConnection();
  270. }
  271. return model;
  272. }
  273. public void OpenConnection()
  274. {
  275. if (this.conn.State != ConnectionState.Open)
  276. this.conn.Open();
  277. }
  278. public void CloseConnection()
  279. {
  280. command.Values.ToList().ForEach(o =>
  281. {
  282. if (o.Transaction != null)
  283. return;
  284. });
  285. if (this.conn.State != ConnectionState.Closed)
  286. this.conn.Close();
  287. }
  288. public void BeginTransation(string Name)
  289. {
  290. tran = conn.BeginTransaction(Name);
  291. }
  292. public void Commit()
  293. {
  294. tran.Commit();
  295. Dispose(tran);
  296. tran = null;
  297. }
  298. public void RollBack()
  299. {
  300. tran.Rollback();
  301. Dispose(tran);
  302. tran = null;
  303. }
  304. }
  305. }
技术分享

  具体类中,主要设计了最重要的执行方法外,还像刚开始所述,设置了List,就是用来存放command对象,在执行完成时候时候它会自己释放。跟这个类配合使用的是异常类:

技术分享
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Dal
  6. {
  7. public class DbException
  8. {
  9. public virtual void Done()
  10. {
  11. }
  12. }
  13. }
技术分享

只有短短几句话,这就是用于使用者想发生异常想它干什么而设置的。

其实封装到这里,整个框架的支持已经形成,但是用户不能直接操作底层,而且还需要怎么对数据库进行实例,所以还要对上进行封装,下一步,往上走,数据库实例部分。

技术分享
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Dal
  6. {
  7. public interface IDbInstance
  8. {
  9. /// <summary>
  10. /// 数据库名称
  11. /// </summary>
  12. string Name
  13. {
  14. get;
  15. }
  16. /// <summary>
  17. /// 获取执行语句类
  18. /// </summary>
  19. IDbExcute Excute
  20. {
  21. get;
  22. }
  23. /// <summary>
  24. /// 获取连接字符串
  25. /// </summary>
  26. string ConnectionString
  27. {
  28. get;
  29. }
  30. /// <summary>
  31. /// 开启事务
  32. /// </summary>
  33. /// <param name="TranName">事务名称</param>
  34. /// <returns></returns>
  35. object getTransation(string TranName);
  36. /// <summary>
  37. /// 获取拼写字符串类
  38. /// </summary>
  39. IDbCode Code
  40. {
  41. get;
  42. }
  43. }
  44. }
技术分享

实现它的具体类包含所有的底层的操作,其实就是可以说是一个数据库实例了,创建一个就相当于一个数据库。里面将上边封装的类都在这里使用。

技术分享
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Reflection;
  8. namespace Dal
  9. {
  10. public class SQLInstance :IDbInstance
  11. {
  12. private SqlConnection conn;
  13. private IDbExcute excute;
  14. Dictionary<string, List<PropertyInfo>> pro;
  15. private string name;
  16. private string connectionString;
  17. private SqlTransaction tran = null;
  18. public SQLInstance(string Name,Dictionary<string,List<PropertyInfo>> pro, string ConnectionString)
  19. {
  20. this.name = Name;
  21. this.connectionString = ConnectionString;
  22. conn = new SqlConnection(ConnectionString);
  23. this.pro = pro;
  24. excute = new SQLExcute(conn,pro);
  25. }
  26. public string Name
  27. {
  28. get
  29. {
  30. return this.name;
  31. }
  32. }
  33. public IDbExcute Excute
  34. {
  35. get
  36. {
  37. return this.excute;
  38. }
  39. }
  40. public string ConnectionString
  41. {
  42. get
  43. {
  44. return this.connectionString;
  45. }
  46. }
  47. public object getTransation(string TranName)
  48. {
  49. return this.conn.BeginTransaction(TranName);
  50. }
  51. public IDbCode Code
  52. {
  53. get
  54. {
  55. return new SQLCode(pro);
  56. }
  57. }
  58. }
  59. }
技术分享

接下来是控制连接的类:

技术分享
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;
  6. namespace Dal
  7. {
  8. public class DbControl
  9. {
  10. //数据库服务
  11. private static Dictionary<string, IDbInstance> Server = new Dictionary<string, IDbInstance>();
  12. //存放缓存
  13. private static Dictionary<string, List<PropertyInfo>> pro = new Dictionary<string, List<PropertyInfo>>();
  14. private static DbControl control = new DbControl();
  15. public static DbControl getInstance()
  16. {
  17. return control;
  18. }
  19. private DbControl()
  20. {
  21. }
  22. public IDbInstance createInstance(string Name,string ConnectionString,string type)
  23. {
  24. string nspace = typeof(IDbInstance).Namespace;
  25. Type t = Type.GetType(nspace + "." + type);
  26. object obj = Activator.CreateInstance(t, new object[] { Name, pro, ConnectionString });
  27. IDbInstance instance = obj as IDbInstance;
  28. Server.Add(Name, instance);
  29. return instance;
  30. }
  31. public IDbInstance this[string Name]
  32. {
  33. get
  34. {
  35. if (Server.ContainsKey(Name))
  36. return Server[Name];
  37. else
  38. return null;
  39. }
  40. }
  41. }
  42. }
技术分享

这里算是顶层的类,最主要就是存放数据库和缓存对象。也许会好奇如果存放数据库,还可以理解,但是放着模型对象的缓存,这是为什么?因为在字符连接,还有具体执行数据库语句时候都会使用到。而且,不仅这个数据库,别的数据库也会使用到,虽然在一个大项目可能用多个数据库,但是他们使用到项目里的模型是一致的吧,因此,将缓存设置在这里,最好不过。而且整个框架只有这一份,其他地方注入使用,就不会耗内存了。

最后就是用户使用的部分,这部分已经屏蔽掉许多底层的部分,只留下通用方法。这些都已经封装好了,直接在这里调用就可以。

技术分享
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. namespace Dal
  7. {
  8. public class DbHelper
  9. {
  10. private IDbInstance instance;
  11. private string Name;
  12. private DbControl control;
  13. private IDbCode Code;
  14. public DbHelper()
  15. {
  16. control = DbControl.getInstance();
  17. }
  18. public DbHelper createConnection(string Name, string ConnectionString, string type)
  19. {
  20. this.Name = Name;
  21. instance = control.createInstance(Name, ConnectionString, type);
  22. return this;
  23. }
  24. public DbHelper ExcuteString(Func<IDbCode,IDbCode> Fun)
  25. {
  26. Code = Fun(this.instance.Code);
  27. return this;
  28. }
  29. public DbHelper createTransation(string Name)
  30. {
  31. this.instance.Excute.BeginTransation(Name);
  32. return this;
  33. }
  34. public DbHelper Rollback()
  35. {
  36. this.instance.Excute.RollBack();
  37. return this;
  38. }
  39. public DbHelper Commit()
  40. {
  41. this.instance.Excute.Commit();
  42. return this;
  43. }
  44. public T ToModel<T>(CommandType Type = CommandType.Text)
  45. where T:class,new()
  46. {
  47. if (this.Code == null)
  48. return null;
  49. return this.instance.Excute.ToModel<T>(this.Code,Type);
  50. }
  51. List<T> ToList<T>(CommandType Type = CommandType.Text)
  52. where T:class,new()
  53. {
  54. if (this.Code == null)
  55. return null;
  56. return this.instance.Excute.ToList<T>(this.Code, Type);
  57. }
  58. object ToResult(CommandType Type = CommandType.Text)
  59. {
  60. if (this.Code == null)
  61. return null;
  62. return this.instance.Excute.ToResult(this.Code, Type);
  63. }
  64. int ExcuteResult(CommandType Type = CommandType.Text)
  65. {
  66. if (this.Code == null)
  67. return -1;
  68. return this.instance.Excute.ExcuteResult(this.Code, Type);
  69. }
  70. DataTable ToDataTable(CommandType Type = CommandType.Text)
  71. {
  72. if (this.Code == null)
  73. return null;
  74. return this.instance.Excute.ToDataTable(this.Code, Type);
  75. }
  76. DataSet ToDataSet(CommandType Type = CommandType.Text)
  77. {
  78. if (this.Code == null)
  79. return null;
  80. return this.instance.Excute.ToDataSet(this.Code, Type);
  81. }
  82. }
  83. }
技术分享

 

  结束:快要熄灯了,没办法在写文章。如果大家对框架有什么不明白,可以在下面评论区问我。这就是更新之后的框架,我觉得还是蛮好用的,虽然还没经过严密的检测。有什么问题,大家也可以指导下,我也在学习中~

C# .NET数据库操作

标签:[]   sts   几句话   文档   实例   规模   .com   反射   http   

人气教程排行