Create your own data access layer 1

Source: Internet
Author: User

In project development, the core work of most developers is how to store and access data. To perform data operations, we must first solve several basic problems:

1. How to establish a connection with a database.

2. How to read data from the database.

3. how to add and modify data tables.

In. NET, ADO. NET easily solves the preceding three problems. We can use DbConnection for connection, DataSet for data storage, and DataAdapter for data update. First look at a piece of code:

 
 
  1. // Create a DbConnection object to connect to the database
  2. SqlConnection conn = new SqlConnection ();
  3. Conn. ConnectionString = "server =.; uid = sa; password = 123456; database = DATA_BASE; max pool size = 300 ;";
  4. // Create a DataAdapter and Command object to read data
  5. SqlDataAdapter da = new SqlDataAdapter ();
  6. SqlCommand cmd = new SqlCommand ();
  7. Cmd. Connection = conn;
  8. Cmd. CommandText = "SELECT * from test ";
  9. Da. SelectCommand = cmd;
  10. // Create a DataSet object, store data, and create a ing with a physical table
  11. DataSet ds = new DataSet ();
  12. Da. Fill (ds, "TEST ");

The preceding Code reads data from the "TEST" table in the Database "DATA_BASE" and stores the data in the DataSet row.

Since the data in the TEST table is read, the next solution is to add, delete, and modify the TEST table.

To add, delete, and modify an object, you must specify InsertCommand, DeleteCommand, and UpdateCommand for the DataAdapter and bind parameters to each Command object:

 
 
  1. // Add data
  2. Cmd = new SqlCommand ();
  3. Cmd. Connection = conn;
  4. Cmd. CommandText = "insert into test (ID, NAME, VAL) VALUES (@ ID, @ NAME, @ VAL )";
  5. SqlParameter param = new SqlParameter ("@ ID", null );
  6. Param. SourceColumn = "ID ";
  7. Cmd. Parameters. Add (param );
  8. Param = new SqlParameter ("@ NAME", null );
  9. Param. SourceColumn = "NAME ";
  10. Cmd. Parameters. Add (param );
  11. Param = new SqlParameter ("@ VAL", null );
  12. Param. SourceColumn = "VAL ";
  13. Cmd. Parameters. Add (param );
  14. Da. InsertCommand = cmd;
  15.  
  16. // Modify data
  17. Cmd = new SqlCommand ();
  18. Cmd. Connection = conn;
  19. Cmd. CommandText = "update test set name = @ NAME, VAL = @ val where id = @ ID ";
  20. Param = new SqlParameter ("@ ID", null );
  21. Param. SourceColumn = "ID ";
  22. Cmd. Parameters. Add (param );
  23. Param = new SqlParameter ("@ NAME", null );
  24. Param. SourceColumn = "NAME ";
  25. Cmd. Parameters. Add (param );
  26. Param = new SqlParameter ("@ VAL", null );
  27. Param. SourceColumn = "VAL ";
  28. Cmd. Parameters. Add (param );
  29. Da. UpdateCommand = cmd;
  30.  
  31. // Delete data
  32. Cmd = new SqlCommand ();
  33. Cmd. Connection = conn; cmd. CommandText = "delete from test where id = @ ID ";
  34. Param = new SqlParameter ("@ ID", null );
  35. Param. SourceColumn = "ID ";
  36. Cmd. Parameters. Add (param );
  37. Da. DeleteCommand = cmd;

After completing the preparation, use DataTable to perform data operations:

 
 
  1. DataTable dt = ds. Tables ["TEST"];
  2. Dt. PrimaryKey = new DataColumn [] {dt. Columns ["ID"]};
  3. Dt. Rows. Add (new object [] {
  4. Guid. newGuid (). toString (), string. format ("test: {0}", DateTime. now), string. format ("test value: {0}", DateTime. now)
  5. });
  6. DataRow dr = dt. Rows. Find ("f8dc2c64-f51a-4e99-bde1-a20069b09c3a ");
  7. If (dr! = Null ){
  8. Dr ["NAME"] = string. Format ("test modification: {0}", DateTime. Now );
  9. }
  10. Dr = dt. Rows. Find ("ed7d079b-81ec-4ba4-bf85-688621e495e7 ");
  11. If (dr! = Null ){
  12. Dr. Delete ();
  13. }

Finally, call the Update method of DataAdapter to save the changed data:

Da. Update (ds, "TEST ");

Using ADO. NET, we have completed the complete database operations.

Note: The above code is the basic principle of using DataAdapter to read and write the database. It is very important that we will use this as the basis for subsequent changes.

Although we can complete data operations, there are still many problems:

1. We only operate on the MSSql database. to operate on Oracle or MySql, we need to define a new Oracle or MySql DATA object. If the Database Type of the operation can be automatically determined by the system, we can ignore the attention to data objects.

2. We have done a lot of preparation work. We only operate on one table. For example, we want to operate on multiple tables with many parameters. In fact, a lot of repeated code will be generated, we need to consider eliminating this code.

If we implement a data access layer. NET object encapsulation, only focus on the actual data operations, not on how the system connects to the database, and how to transmit parameters, then our needs are basically met.

We can first assume that the following results need to be achieved, in the form of a pseudo code:

 
 
  1. Create a data executor: DataExecuter: execObj;
  2. Create a data ing object: DataMapping map;
  3. Data Set filled by ing object: map. Fill (sqlText, "TEST", ds );
  4. Set the ing object Update command: map. SetCommands (Insert | Update | Delete, ds );
  5. DataTable performs addition, deletion, and modification operations.
  6. The data performer performs the final change operation: execObj. Update (ds );

I will see how the above assumptions are implemented step by step.

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.