基于.NET平台的分层架构实战(七)——数据访问层的第一种实现:Access+SQL

经过上面篇文章的介绍,整个系统的框架算是基本搭建完了,下面,我们要具体实现各个层次。关于数据访问层的实现,我准备讨论三种实现方式,这一篇文章讨论第一种:Access+动态生成SQL。

      顾名思义,这种实现将使用Access作为后台数据库,而操作方式也是最基本的使用SQL命令。

      在具体编写实现代码之前,我们需要做一些准备工作:

      第一步,我们要将Access数据库搭建完成,具体做法如下。

      在Web工程下新建一个文件夹,命名为AccessData,并在其中新建一个mdb文件(即Access数据库文件),按照前面介绍过的数据库设计构架,将数据表及表间关系建好,这里不再赘述。

      第二步,我们要进行一些配置
      打开Web工程下的Web.config文件,在其中的appSettings节点下,添加如下键值:
      <add key="AccessConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={DBPath}"/>
      <add key="AccessPath" value="~/AccessData/AccessDatabase.mdb"/>
      第一条为Access的连接字符串,第二条为Access数据库文件的路径,其中“~”表示网站根目录。

      第三步,新建一个工程。
      我们要新建一个工程AccessDAL,用来存放Access数据访问层的代码。

      准备工作做完了,现在来实现具体的代码。

      1.编写数据访问助手类
      因为很多数据访问操作流程很相似,所以,这里将一些可复用的代码抽取出来,编写成助手类,以此减少代码量,提高代码复用性。
      这个助手类放在AccessDAL下,叫AccessDALHelper,主要负责Access数据库的访问。它包括三个方法:
      GetConnectionString:从配置文件中读取配置项,组合成连接字符串。
      ExecuteSQLNonQuery:执行指定SQL语句,不返回任何值,一般用于Insert,Delete,Update命令。
      ExecuteSQLDataReader:执行SQL语句返回查询结果,一般用于Select命令。
      具体代码如下:

AccessDALHelper.cs:

AccessDALHelper

  1. 1using System;
  2. 2using System.Web;
  3. 3using System.Web.Caching;
  4. 4using System.Configuration;
  5. 5using System.Data;
  6. 6using System.Data.OleDb;
  7. 7using NGuestBook.Utility;
  8. 8
  9. 9namespace NGuestBook.AccessDAL
  10. 10{
  11. 11    /** <summary>
  12. 12    /// Access数据库操作助手
  13. 13    /// </summary>
  14. 14    public sealed class AccessDALHelper
  15. 15    {
  16. 16        /** <summary>
  17. 17        /// 读取Access数据库的连接字符串
  18. 18        /// 首先从缓存里读取,如果不存在则到配置文件中读取,并放入缓存
  19. 19        /// </summary>
  20. 20        /// <returns>Access数据库的连接字符串</returns>
  21. 21        private static string GetConnectionString()
  22. 22        {
  23. 23            if (CacheAccess.GetFromCache("AccessConnectionString") != null)
  24. 24            {
  25. 25                return CacheAccess.GetFromCache("AccessConnectionString").ToString();
  26. 26            }
  27. 27            else
  28. 28            {
  29. 29                string dbPath = ConfigurationManager.AppSettings["AccessPath"];
  30. 30                string dbAbsolutePath = HttpContext.Current.Server.MapPath(dbPath);
  31. 31                string connectionString = ConfigurationManager.AppSettings["AccessConnectionString"];
  32. 32
  33. 33                CacheDependency fileDependency = new CacheDependency(HttpContext.Current.Server.MapPath("Web.Config"));
  34. 34                CacheAccess.SaveToCache("AccessConnectionString", connectionString.Replace("{DBPath}", dbAbsolutePath), fileDependency);
  35. 35
  36. 36                return connectionString.Replace("{DBPath}", dbAbsolutePath);
  37. 37            }
  38. 38        }
  39. 39
  40. 40        /** <summary>
  41. 41        /// 执行SQL语句并且不返回任何值
  42. 42        /// </summary>
  43. 43        /// <param name="SQLCommand">所执行的SQL命令</param>
  44. 44        /// <param name="parameters">参数集合</param>
  45. 45        public static void ExecuteSQLNonQuery(string SQLCommand,OleDbParameter[] parameters)
  46. 46        {
  47. 47            OleDbConnection connection = new OleDbConnection(GetConnectionString());
  48. 48            OleDbCommand command = new OleDbCommand(SQLCommand, connection);
  49. 49
  50. 50            for (int i = 0; i < parameters.Length; i++)
  51. 51            {
  52. 52                command.Parameters.Add(parameters);
  53. 53            }
  54. 54
  55. 55            connection.Open();
  56. 56            command.ExecuteNonQuery();
  57. 57            connection.Close();
  58. 58        }
  59. 59
  60. 60        /** <summary>
  61. 61        /// 执行SQL语句并返回包含查询结果的DataReader
  62. 62        /// </summary>
  63. 63        /// <param name="SQLCommand">所执行的SQL命令</param>
  64. 64        /// <param name="parameters">参数集合</param>
  65. 65        /// <returns></returns>
  66. 66        public static OleDbDataReader ExecuteSQLDataReader(string SQLCommand,OleDbParameter[] parameters)
  67. 67        {
  68. 68            OleDbConnection connection = new OleDbConnection(GetConnectionString());
  69. 69            OleDbCommand command = new OleDbCommand(SQLCommand, connection);
  70. 70
  71. 71            for (int i = 0; i < parameters.Length; i++)
  72. 72            {
  73. 73                command.Parameters.Add(parameters);
  74. 74            }
  75. 75
  76. 76            connection.Open();
  77. 77            OleDbDataReader dataReader = command.ExecuteReader();
  78. 78            //connection.Close();
  79. 79
  80. 80            return dataReader;
  81. 81        }
  82. 82    }
  83. 83}
复制代码

2.实现具体的数据访问操作类
      因为前面已经定义了数据访问层接口,所以实现数据访问操作类就是很机械的工作了。下面仅以Admin的数据访问操作类为例:

AdminDAL:

AdminDAL

  1.   1using System;
  2.   2using System.Collections.Generic;
  3.   3using System.Text;
  4.   4using System.Data;
  5.   5using System.Data.OleDb;
  6.   6using NGuestBook.IDAL;
  7.   7using NGuestBook.Entity;
  8.   8
  9.   9namespace NGuestBook.AccessDAL
  10. 10{
  11. 11    public class AdminDAL : IAdminDAL
  12. 12    {
  13. 13        /** <summary>
  14. 14        /// 插入管理员
  15. 15        /// </summary>
  16. 16        /// <param name="admin">管理员实体类</param>
  17. 17        /// <returns>是否成功</returns>
  18. 18        public bool Insert(AdminInfo admin)
  19. 19        {
  20. 20            string SQLCommand = "insert into [TAdmin]([Name],[Password]) values(@name,@password)";
  21. 21            OleDbParameter[] parameters ={
  22. 22                new OleDbParameter("name",admin.Name),
  23. 23                new OleDbParameter("password",admin.Password)
  24. 24            };
  25. 25
  26. 26            try
  27. 27            {
  28. 28                AccessDALHelper.ExecuteSQLNonQuery(SQLCommand, parameters);
  29. 29                return true;
  30. 30            }
  31. 31            catch
  32. 32            {
  33. 33                return false;
  34. 34            }
  35. 35        }
  36. 36
  37. 37        /** <summary>
  38. 38        /// 删除管理员
  39. 39        /// </summary>
  40. 40        /// <param name="id">欲删除的管理员的ID</param>
  41. 41        /// <returns>是否成功</returns>
  42. 42        public bool Delete(int id)
  43. 43        {
  44. 44            string SQLCommand = "delete from [TAdmin] where [ID]=@id";
  45. 45            OleDbParameter[] parameters ={
  46. 46                new OleDbParameter("id",id)
  47. 47            };
  48. 48
  49. 49            try
  50. 50            {
  51. 51                AccessDALHelper.ExecuteSQLNonQuery(SQLCommand, parameters);
  52. 52                return true;
  53. 53            }
  54. 54            catch
  55. 55            {
  56. 56                return false;
  57. 57            }
  58. 58        }
  59. 59
  60. 60        /** <summary>
  61. 61        /// 更新管理员信息
  62. 62        /// </summary>
  63. 63        /// <param name="admin">管理员实体类</param>
  64. 64        /// <returns>是否成功</returns>
  65. 65        public bool Update(AdminInfo admin)
  66. 66        {
  67. 67            string SQLCommand = "update [TAdmin] set [Name]=@name,[Password]=@password where [ID]=@id";
  68. 68            OleDbParameter[] parameters ={
  69. 69                new OleDbParameter("id",admin.ID),
  70. 70                new OleDbParameter("name",admin.Name),
  71. 71                new OleDbParameter("password",admin.Password)
  72. 72            };
  73. 73
  74. 74            try
  75. 75            {
  76. 76                AccessDALHelper.ExecuteSQLNonQuery(SQLCommand, parameters);
  77. 77                return true;
  78. 78            }
  79. 79            catch
  80. 80            {
  81. 81                return false;
  82. 82            }
  83. 83        }
  84. 84
  85. 85        /** <summary>
  86. 86        /// 按ID取得管理员信息
  87. 87        /// </summary>
  88. 88        /// <param name="id">管理员ID</param>
  89. 89        /// <returns>管理员实体类</returns>
  90. 90        public AdminInfo GetByID(int id)
  91. 91        {
  92. 92            string SQLCommand = "select * from [TAdmin] where [ID]=@id";
  93. 93            OleDbParameter[] parameters ={
  94. 94                new OleDbParameter("id",id)
  95. 95            };
  96. 96
  97. 97            try
  98. 98            {
  99. 99                OleDbDataReader dataReader = AccessDALHelper.ExecuteSQLDataReader(SQLCommand, parameters);
  100. 100                if (!dataReader.HasRows)
  101. 101                {
  102. 102                    throw new Exception();
  103. 103                }
  104. 104
  105. 105                AdminInfo admin = new AdminInfo();
  106. 106                dataReader.Read();
  107. 107                admin.ID=(int)dataReader["ID"];
  108. 108                admin.Name=(string)dataReader["Name"];
  109. 109                admin.Password=(string)dataReader["Password"];
  110. 110
  111. 111                return admin;
  112. 112            }
  113. 113            catch
  114. 114            {
  115. 115                return null;
  116. 116            }
  117. 117        }
  118. 118
  119. 119        /** <summary>
  120. 120        /// 按用户名及密码取得管理员信息
  121. 121        /// </summary>
  122. 122        /// <param name="name">用户名</param>
  123. 123        /// <param name="password">密码</param>
  124. 124        /// <returns>管理员实体类,不存在时返回null</returns>
  125. 125        public AdminInfo GetByNameAndPassword(string name, string password)
  126. 126        {
  127. 127            string SQLCommand = "select * from [TAdmin] where [Name]=@name and [Password]=@password";
  128. 128            OleDbParameter[] parameters ={
  129. 129                new OleDbParameter("name",name),
  130. 130                new OleDbParameter("password",password),
  131. 131            };
  132. 132
  133. 133            try
  134. 134            {
  135. 135                OleDbDataReader dataReader = AccessDALHelper.ExecuteSQLDataReader(SQLCommand, parameters);
  136. 136                if (!dataReader.HasRows)
  137. 137                {
  138. 138                    throw new Exception();
  139. 139                }
  140. 140
  141. 141                AdminInfo admin = new AdminInfo();
  142. 142                dataReader.Read();
  143. 143                admin.ID = (int)dataReader["ID"];
  144. 144                admin.Name = (string)dataReader["Name"];
  145. 145                admin.Password = (string)dataReader["Password"];
  146. 146
  147. 147                return admin;
  148. 148            }
  149. 149            catch
  150. 150            {
  151. 151                return null;
  152. 152            }
  153. 153        }
  154. 154
  155. 155        /** <summary>
  156. 156        /// 按管理员名取得管理员信息
  157. 157        /// </summary>
  158. 158        /// <param name="name">管理员名</param>
  159. 159        /// <returns>管理员实体类</returns>
  160. 160        public AdminInfo GetByName(string name)
  161. 161        {
  162. 162            string SQLCommand = "select * from [TAdmin] where [Name]=@name";
  163. 163            OleDbParameter[] parameters ={
  164. 164                new OleDbParameter("name",name),
  165. 165            };
  166. 166
  167. 167            try
  168. 168            {
  169. 169                OleDbDataReader dataReader = AccessDALHelper.ExecuteSQLDataReader(SQLCommand, parameters);
  170. 170                if (!dataReader.HasRows)
  171. 171                {
  172. 172                    throw new Exception();
  173. 173                }
  174. 174
  175. 175                AdminInfo admin = new AdminInfo();
  176. 176                dataReader.Read();
  177. 177                admin.ID = (int)dataReader["ID"];
  178. 178                admin.Name = (string)dataReader["Name"];
  179. 179                admin.Password = (string)dataReader["Password"];
  180. 180
  181. 181                return admin;
  182. 182            }
  183. 183            catch
  184. 184            {
  185. 185                return null;
  186. 186            }
  187. 187        }
  188. 188
  189. 189        /** <summary>
  190. 190        /// 取得全部管理员信息
  191. 191        /// </summary>
  192. 192        /// <returns>管理员实体类集合</returns>
  193. 193        public IList<AdminInfo> GetAll()
  194. 194        {
  195. 195            string SQLCommand = "select * from [TAdmin]";
  196. 196            try
  197. 197            {
  198. 198                OleDbDataReader dataReader = AccessDALHelper.ExecuteSQLDataReader(SQLCommand, null);
  199. 199                if (!dataReader.HasRows)
  200. 200                {
  201. 201                    throw new Exception();
  202. 202                }
  203. 203
  204. 204                IList<AdminInfo> adminCollection = new List<AdminInfo>();
  205. 205                int i = 0;
  206. 206                while (dataReader.Read())
  207. 207                {
  208. 208                    AdminInfo admin = new AdminInfo();
  209. 209                    admin.ID = (int)dataReader["ID"];
  210. 210                    admin.Name = (string)dataReader["Name"];
  211. 211                    admin.Password = (string)dataReader["Password"];
  212. 212
  213. 213                    adminCollection.Add(admin);
  214. 214                    i++;
  215. 215                }
  216. 216
  217. 217                return adminCollection;
  218. 218            }
  219. 219            catch
  220. 220            {
  221. 221                return null;
  222. 222            }
  223. 223        }
  224. 224    }
  225. 225}
复制代码

可以看到,这里主要包括三种类型的操作,一种是修改型,如Insert;一种是返回单个实体类型,如GetByID;还有一种是返回实体类集合型,如GetAll。
      MessageDAL和CommentDAL的实现非常相似,在这里不再赘述。

转载于:https://www.cnblogs.com/hliq/archive/2011/03/26/2087207.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值