当前位置:编程学习 > asp >>

初识三层架构

复杂项目不能把SQL语句直接写到程序里,不模块化、难以维护,应该采用三层架构。Web开发中的三层架构也是同样的结构。 模型层Model;数据访问层DAL(Data Access Layer);业务逻辑层BLL(business logic layer )。实体类就是Model;对数据进行操作的代码写在DAL中,一般就是SQL语句,DAL只有对数据的操作;BLL调用DAL中的代码进行逻辑操作SQL语句一般只应该出现在DAL中。 三层:UI(界面,User Inte易做图ce)、BLL、DAL。Model是在三层之间进行数据传递的。UI层调用BLL、BLL调用DAL,数据用Model传递,UI不能直接调用DAL。
  SQLHelper
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace 三层架构.DAL
{
    class SQLHelper
    {
        public static readonly string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
        /// <summary>
        /// 执行非查询语句
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <param name="parameters">传入变量</param>
        /// <returns>影响行数</returns>
        public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
        {
            using (SqlConnection con = new SqlConnection(conStr))
            {
                con.Open();
                using (SqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = sql;
                    if (parameters != null)
                    {
                        foreach (SqlParameter param in parameters)
                        {
                            cmd.Parameters.Add(param);
                        }
                    }
                    return cmd.ExecuteNonQuery();
                }
            }
        }
        /// <summary>
        /// 执行非查询语句
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <param name="parameters">传入变量</param>
        /// <returns>返回查询结果中的第一行第一列的值</returns>
        public static object ExecuteScalar(string sql, params SqlParameter[] parameters)
        {
            using (SqlConnection con = new SqlConnection(conStr))
            {
                con.Open();
                using (SqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = sql;
                    if (parameters != null)
                    {
                        foreach (SqlParameter param in parameters)
                        {
                            cmd.Parameters.Add(param);
                        }
                    }
                    return cmd.ExecuteScalar();
                }
            }
        }
        public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters)
        {
            using (SqlConnection con = new SqlConnection(conStr))
            {
                con.Open();
                using (SqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = sql;
                    if (parameters != null)
                    {
                        foreach (SqlParameter

补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,