基于.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:

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


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

AdminDAL:

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


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值