The first implementation of the. NET-based layered architecture (7) data access layer:

Source: Internet
Author: User
After the introduction in the above article, the entire system framework is basically complete. Below, we need to implement each layer. For the implementation of the data Access layer, I will discuss three implementation methods. This article discusses the first one: Access + dynamic generation of SQL. As the name suggests, this implementation uses Access as the background database, and

After the introduction in the above article, the entire system framework is basically complete. Below, we need to implement each layer. For the implementation of the data Access layer, I will discuss three implementation methods. This article discusses the first one: Access + dynamic generation of SQL. As the name suggests, this implementation uses Access as the background data library, while

After the introduction in the previous article, the framework of the entire system is basically complete. Below, we needImplementationEach layer. AboutDataAccessLayerImplementation, I am going to discuss three typesImplementationMethod, discussed in this articleFirstType: Access + dynamic generation of SQL.

As the name suggestsImplementationUse Access as the backgroundDataDatabase, and the operation method is also the most basic use of SQL commands.

WriteImplementationBefore the code, we need to do some preparation work:

FirstStep.DataAfter the library is set up, follow these steps.

Create a folder named AccessData in the Web Project, and create an mdb File (AccessDataLibrary files), according toDataLibrary Design architectureDataThe relationship between the table and the table is created.

Step 2: perform some configuration.
Open the Web. config file in the Web project, and add the following key values under the deleettings node:


FirstThe connection string is Access, and the second is Access.DataPath of the library file, where "~" Indicates the root directory of the website.

Step 3: Create a project.
We need to create a new project AccessDAL to store AccessDataAccessLayer Code.

Now the preparation is complete.ImplementationSpecific code.

1. WriteDataAccessHelper class
Because manyDataAccessThe operation process is very similar. Therefore, some reusable code is extracted here and written as helper classes to reduce the amount of code and improve code reusability.
This helper class is stored in AccessDAL and called AccessDALHelper. It is mainly responsible for AccessDataLibraryAccess. It includes three methods:
GetConnectionString: Read configuration items from the configuration file and combine them into connection strings.
ExecuteSQLNonQuery: executes the specified SQL statement without returning any value. It is generally used for the Insert, Delete, and Update commands.
ExecuteSQLDataReader: Execute an SQL statement to return the query result. It is generally used for the Select command.
The Code is as follows:

AccessDALHelper. cs:

AccessDALHelper

  1. 1 using System;
  2. 2 using System. Web;
  3. 3 using System. Web. Caching;
  4. 4 using System. Configuration;
  5. 5 using System. Data;
  6. 6 using System. Data. OleDb;
  7. 7 using NGuestBook. Utility;
  8. 8
  9. 9 namespace NGuestBook. AccessDAL
  10. 10 {
  11. 11 /**////
  12. 12 // AccessDataDatabase Operation Assistant
  13. 13 ///
  14. 14 public sealed class AccessDALHelper
  15. 15 {
  16. 16 /**////
  17. 17 // read AccessDataDatabase connection string
  18. 18 // read from the cache first, read from the configuration file if it does not exist, and put it in the cache
  19. 19 ///
  20. 20 /// Access DataDatabase connection string
  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. receivettings ["AccessPath"];
  30. 30 string dbAbsolutePath = HttpContext. Current. Server. MapPath (dbPath );
  31. 31 string connectionString = ConfigurationManager. receivettings ["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 /**////
  41. 41 // execute the SQL statement without returning any value
  42. 42 ///
  43. 43 ///The executed SQL command
  44. 44 ///Parameter Set
  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 /**////
  61. 61 // execute the SQL statement and return the DataReader containing the query result
  62. 62 ///
  63. 63 ///The executed SQL command
  64. 64 ///Parameter Set
  65. 65 ///
  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.ImplementationSpecificDataAccessOperation
Because we have already definedDataAccessLayer interface, soImplementationDataAccessThe operation class is very mechanical. Only the AdminDataAccessOperation class:

AdminDAL:

AdminDAL

  1. 1 using System;
  2. 2 using System. Collections. Generic;
  3. 3 using System. Text;
  4. 4 using System. Data;
  5. 5 using System. Data. OleDb;
  6. 6 using NGuestBook. IDAL;
  7. 7 using NGuestBook. Entity;
  8. 8
  9. 9 namespace NGuestBook. AccessDAL
  10. 10 {
  11. 11 public class AdminDAL: IAdminDAL
  12. 12 {
  13. 13 /**////
  14. 14 // Insert the Administrator
  15. 15 ///
  16. 16 ///Administrator entity class
  17. 17 /// Successful or not
  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 /**////
  38. 38 // Delete the Administrator
  39. 39 ///
  40. 40 ///ID of the Administrator to delete
  41. 41 /// Successful or not
  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 /**////
  61. 61 // update administrator Information
  62. 62 ///
  63. 63 ///Administrator entity class
  64. 64 /// Successful or not
  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 /**////
  86. 86 // obtain administrator information by ID
  87. 87 ///
  88. 88 ///Administrator ID
  89. 89 /// Administrator entity class
  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 /**////
  120. 120 // obtain administrator information by user name and password
  121. 121 ///
  122. 122 ///User Name
  123. 123 ///Password
  124. 124 /// Administrator entity class. If the specified object does not exist, null is returned.
  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 /**////
  156. 156 // obtain administrator information by Administrator name
  157. 157 ///
  158. 158 ///Administrator name
  159. 159 /// Administrator entity class
  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 /**////
  190. 190 // obtain all administrator Information
  191. 191 ///
  192. 192 /// Administrator entity class set
  193. 193 public IList 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 adminCollection = new List ();
  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}

It can be seen that there are three types of operations, one is the modified type, such as Insert; the other is to return a single object type, such as GetByID; and the other is the collection type of the returned object class, for example, GetAll.
MessageDAL and CommentDALImplementationVery similar. I will not go into details here.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.