Architecture - Layer -DAL: DAL

ylbtech- architecture - layer -DAL: DAL

Is the abbreviation DAL data access layer, that is, the data access layer (the Data Access Layer) . Its function is mainly responsible for accessing the database . Simply put, is to realize the data table Select (query), Insert (insert), Update (update), Delete (delete) and other operations .

1. Back to top
1、
Chinese name: DAL data access layer
English name: Data Access Layer
Structure of layers: Layer 3
Nickname: DAL layer
Definitions: mainly responsible for database access
Disciplines: Computer Technology

table of Contents

2、
2. Return to top
1、

basic introduction

In enterprise applications, there is little not to deal with the database. As long as the database is used, there is the demand for business data persisted to the database .
In the actual project development process, some directly using JDBC technology database persistence operations, some use the current good use ORM framework for database persistence operations.
The main role of extracting a database access layer is isolated, things dealing with the database are placed in the data access layer resolved, just call the data access layer in the service layer can, and do not have specific ORM layer implementation phase coupling.
Database access layer: also known as the DAL, sometimes also known as persistence layer , its main function is responsible for the database access. Simply put, is to realize the Select data table (query), Insert (insert), Update (update), Delete (delete) operations. If you want to join ORM thought, it will include mapping between objects and tables, as well as persistent objects operating entity .
Talked about database access layer, I must mention three-tier architecture, the application system will usually be divided into: the presentation layer, business logic and database access layer . This design goal is to achieve "high cohesion, low coupling" design concept. Database access layer three-tier system is only responsible for storing and reading data . Business logic as the database access method upper layer, the internal layer provides database access calls to complete store and read data. Database access layer and should be independent of the underlying database, database access layer good dynamic switching scheme is able to implement different types of databases does not modify the program code on the basis of the above functions. We are more familiar approach is to complete the handover of the underlying database via XML configuration file . At present, many popular database access layer frame in this way is to implement existing database dynamically switched . Data access layer in the application data can be persisted to a storage medium, usually a relational database is a database we use, the use of the data model is an object model, which requires database access layer to achieve the object model and the relational model direct, mutual conversion .
 

Feature

Three-tier structure:
1. The presentation layer (USL): mainly showing the WEB, may be represented as WINFORM manner. If the logical layer quite powerful and perfect, regardless of how to define and change the presentation layer, logic layer can improve the delivery of services.
2. Business Logic Layer (BLL): main operation-specific issues , the operation can also be understood paired data layer, the data processing business logic. If the data layer is a building block, logic layer that is to build on these building blocks.
3. Data Access Layer (DAL): main raw data ( database or text file stored in the form data ) of the operational layer , rather than the raw data, that is, operations on the data, rather than the database, specifically providing data services to business logic or presentation layer.
 

design

Read and write operations for data access layer DataAccessLayer database data, the layer comprising only one class file Database.cs. We need to create the class file in some way in order to complete the establishment of a database connection, SQL statements submitted to the database and return the corresponding operating results and other functions.
Add the class file
Folder to add a new entry in the DataAccessLayer file, select the template in the "Select New Item" dialog box for the "class" to the class file is named Database.cs, click the "Add" button.
Namespace references
As the class code to use ADO.NET related objects, you need to reference the following namespace:
using System.Data.SqlClient;
Class File Structure
The Database class is defined in the code namespace MessageBoard. DataAccessLayer defined in the pay code structure is as follows:
namespace MessageBoard.DataAccessLayer 
{ 
    public  class Database 
    { 
        custom method () 
        {} 
    } 
}
In the method of adding the class Database
(1) DBCon () method
Function: Returns SqlConnection object database connection parameters, no parameters belonging function. code show as below:
a using the System.Data.SqlClient; 

public  class DBConnection 
{ 
    the SqlConnection conn = null ; 

    public DBConnection () 
    { 
        // TODO: create objects
         // Windows Authentication
         // conn = new new the SqlConnection ( "Server = .; Database = db1; Integrated Security SSPI = "); // local connection 

        // SQL Server authentication
         // , locahost, 127.0.0.1 represents the local.
         // conn.ConnectionString =" Server = .; Database = db1; SA Uid =; Pwd = 123456 " ;  
         // conn.ConnectionString = "Server = locahost; Database = db1; SA Uid =; Pwd = 123456"; 
        //conn.ConnectionString = "Server=127.0.0.1;Database=db1;Uid=sa;Pwd=123456";
        conn = new SqlConnection( "Server=.;User ID=sa;Password=123456;Initial Catalog=db1;Min Pool Size=30;Max Pool Size=100;Connect Timeout=60" );  // 远程连接
    }

    public SqlConnection Conn
    {
        get { return conn; }
        set { conn = value; }
    }
}
Also use the following method returns database connection string:
// 创建Conn对象
SqlConnection conn = new DBConnection().Conn;
(2)GetDataSet(String)方法
Function: reception came SQL statements, make queries, the query returns a result set. The parameters of the method is character type, as follows:
(3) ExecuteSQL (String) method
Function: reception came SQL statements, performing non-query operation, complete information is written to the message database operations. The method parameters is a string type, as follows:
2、
3. Code Top
·DBConnection.cs
a using the System.Data.SqlClient; 

public  class DBConnection 
{ 
    the SqlConnection conn = null ; 

    public DBConnection () 
    { 
        // TODO: create objects
         // Windows Authentication
         // conn = new new the SqlConnection ( "Server = .; Database = db1; Integrated Security SSPI = "); // local connection 

        // SQL Server authentication
         // , locahost, 127.0.0.1 represents the local.
         // conn.ConnectionString =" Server = .; Database = db1; SA Uid =; Pwd = 123456 " ;  
         // conn.ConnectionString = "Server = locahost; Database = db1; SA Uid =; Pwd = 123456"; 
        //conn.ConnectionString = "Server=127.0.0.1;Database=db1;Uid=sa;Pwd=123456";
        conn = new SqlConnection( "Server=.;User ID=sa;Password=123456;Initial Catalog=db1;Min Pool Size=30;Max Pool Size=100;Connect Timeout=60" );  // 远程连接
    }

    public SqlConnection Conn
    {
        get { return conn; }
        set { conn = value; }
    }
}
View Code
·ProductInfo.cs
public class ProductInfo
{
    public int? ProductId { get; set; }
    public string ProductName { get; set; }
    public decimal? UnitPrice { get; set; }
    public string Type { get; set; }

}
·Product.cs
using System.Collections.Generic;

using System.Data.SqlClient;

public class Product
{
    /// <summary>
    /// ylb: 1,GetAll
    /// remark: 获取所有产品,并以productId降序排列
    /// </summary>
    /// <returns></returns>
    public IList<ProductInfo> GetAll()
    {

        IList<ProductInfo> dals = new List<ProductInfo>();

        string sql = "select productId,productName,unitPrice,type from Product";

        SqlConnection conn = new DBConnection().Conn;
        SqlCommand com = conn.CreateCommand();

        com.CommandText = sql;
        conn.Open();
        try
        {
            SqlDataReader sdr = com.ExecuteReader();
            while( sdr.Read() )
            {
                ProductInfo dal = new ProductInfo()
                {
                    ProductId = sdr.GetInt32( 0 ),
                    ProductName = sdr.GetString( 1 ),
                    UnitPrice = sdr.GetDecimal( 2 ),
                    Type = sdr.GetString( 3 )
                };

                dals.Add( dal );
            }
        }
        finally
        {
            conn.Close();
        }
        return dals;
    }

    /// <summary>
    /// ylb: 2,Add
    /// remark: 添加一个产品
    /// field: productName,unitPrice,type
    /// </summary>
    /// <param name="dal"></param>
    public void Add( ProductInfo dal )
    {

        string sql = "insert into Product(productName,unitPrice,type) values(@productName,@unitPrice,@type)";

        SqlConnection conn = new DBConnection().Conn;
        SqlCommand com = conn.CreateCommand();

        com.Parameters.Add( new SqlParameter( "@productName", dal.ProductName ) );
        com.Parameters.Add( new SqlParameter( "@unitPrice", dal.UnitPrice ) );
        com.Parameters.Add( new SqlParameter( "@type", dal.Type ) );
        com.CommandText = sql;

        conn.Open();
        try
        {
            com.ExecuteNonQuery();
        }
        finally
        {
            conn.Close();
        }

    }

    /// <summary>
    /// ylb: 3,GetModel
    /// remark: 获得一个实体对象,根据productId
    /// </summary>
    /// <param name="productId"></param>
    /// <returns></returns>
    public ProductInfo GetModel( int productId )
    {
        ProductInfo dal = null;

        string sql = "select productId,productName,unitPrice,type from Product where productId=@productId";

        SqlConnection conn = new DBConnection().Conn;
        SqlCommand com = conn.CreateCommand();

        com.Parameters.Add( new SqlParameter( "@productId", productId ) );
        com.CommandText = sql;
        conn.Open();
        try
        {
            SqlDataReader sdr = com.ExecuteReader();
            while( sdr.Read() )
            {
                dal = new ProductInfo()
                {
                    ProductId = sdr.GetInt32( 0 ),
                    ProductName = sdr.GetString( 1 ),
                    UnitPrice = sdr.GetDecimal( 2 ),
                    Type = sdr.GetString( 3 )
                };
            }
        }
        finally
        {
            conn.Close();
        }
        return dal;
    }

    /// <summary>
    /// ylb: 4,Update
    /// remark: 修改一条信息 ,根据productId
    /// </summary>
    /// <param name="dal"></param>
    public void Update( ProductInfo dal )
    {

        string sql = "update Product set productName=@productName,unitPrice=@unitPrice,type=@type where productId=@productId";

        SqlConnection conn = new DBConnection().Conn;
        SqlCommand com = conn.CreateCommand();

        com.Parameters.Add( new SqlParameter( "@productName", dal.ProductName ) );
        com.Parameters.Add( new SqlParameter( "@unitPrice", dal.UnitPrice ) );
        com.Parameters.Add( new SqlParameter( "@type", dal.Type ) );
        com.Parameters.Add( new SqlParameter( "@productId", dal.ProductId ) );
        com.CommandText = sql;

        conn.Open();
        try
        {
            com.ExecuteNonQuery();
        }
        finally
        {
            conn.Close();
        }

    }

    /// <summary>
    /// ylb: 5,Delete
    /// remark: 删除一条信息,根据productId
    /// </summary>
    /// <param name="productId"></param>
    public void Delete( int productId )
    {

        string sql = "delete Product where productId=@productId";

        SqlConnection conn = new DBConnection().Conn;
        SqlCommand com = conn.CreateCommand();

        com.Parameters.Add( new SqlParameter( "@productId", productId ) );
        com.CommandText = sql;

        conn.Open();
        try
        {
            com.ExecuteNonQuery();
        }
        finally
        {
            conn.Close();
        }
    }
}
View Code
·
4. Top
 
5. Top
1、
2、
 
6. Back to top
 
warn Author: ylbtech
Source: http://ylbtech.cnblogs.com/
This article belongs to the author and blog Park total, welcome to reprint, but without the author's consent declared by this section must be retained, and given the original connection in the apparent position of the article page, otherwise We reserve the right to pursue legal responsibilities.

Guess you like

Origin www.cnblogs.com/storebook/p/11604226.html