asp.net 中第三层(数据访问层)的 Db Manager 类

Posted

技术标签:

【中文标题】asp.net 中第三层(数据访问层)的 Db Manager 类【英文标题】:Db Manager class for third tier (Data Access Layer) in asp.net 【发布时间】:2018-07-06 10:12:50 【问题描述】:

我正在使用 3 层架构来构建网站。为此,我创建了一个名为 DB Manager 的类。

这是课程

namespace DAL

    class DBManager
    
        private static DataTable dt = new DataTable();
        private static string ConnectionString = System.Configuration.ConfigurationManager.AppSettings["SQLSERVER"];

        public static int ExecuteNonQuery(string query)
        
            int result;
            SqlConnection con = new SqlConnection(ConnectionString);
            SqlCommand command = new SqlCommand(query, con);

            try
            
                con.Open();
                result = command.ExecuteNonQuery();
                con.Close();
            
            catch
            
                result = -1;
            
            finally
            
                con.Close();
            

            return result;
        

        public static DataTable ExecuteDataTable(string query)
        
            SqlConnection con = new SqlConnection(ConnectionString);
            SqlDataAdapter da = new SqlDataAdapter();
            dt = new DataTable();

            try
            
                con.Open();
                da.SelectCommand = new SqlCommand(query, con);
                con.Close();
                da.Fill(dt);
            
            catch
            
                dt.Rows.Clear();
            

            return dt;
        

        public static string ExecuteScaler(string query)
        
            SqlConnection con = new SqlConnection(ConnectionString);
            SqlDataAdapter da = new SqlDataAdapter();
            string result = string.Empty;

            try
            
                con.Open();
                da.SelectCommand = new SqlCommand(query, con);
                con.Close();
                dt = new DataTable();
                da.Fill(dt);

                if (dt.Rows.Count == 1 && dt.Columns.Count == 1)
                
                    result = dt.Rows[0][0].ToString();
                

            
            catch
            
                result = string.Empty;
            

            return result;
        

        public static bool ExecuteReader(string query)
        
            bool result = false;
            SqlConnection con = new SqlConnection(ConnectionString);
            SqlDataAdapter da = new SqlDataAdapter();

            try
            
                con.Open();
                da.SelectCommand = new SqlCommand(query, con);
                con.Close();
                dt = new DataTable();
                da.Fill(dt);

                if (dt.Rows.Count == 1 && dt.Columns.Count == 1)
                
                    if (dt.Rows[0][0].ToString() == "true")
                    
                        result = true;
                    
                    else
                    
                        result = false;
                    
                
             catch (Exception)
            
                result = false;
            

            return result;
        
    

当我这样查询时

query = "insert into client(account_id, name, receive_email) values(" + accountId + ", '" + clientBLL.name + "', " + clientBLL.receiveMail + ");";

但是这种查询方法应该是非常糟糕的主意。好的方法是向 SqlCommand 中提供要插入或检索哪些数据的参数。

这样

query = @"insert into accounts(email, password, user_type) output inserted.id values(@email, @password, @userType);";
cmd.Parameters.Add("email", SqlDbType.NVarChar).Value = bll.email;
cmd.Parameters.Add("password", SqlDbType.VarBinary).Value = bll.password;
cmd.Parameters.Add("userType", SqlDbType.Bit).Value = 0;

但是我的 DB Manager 类不支持这种方法。我想要一个支持这种 Sql 命令查询方法的 Db Manager 类,而不是旧的(我之前表达过的)。我该怎么做。

【问题讨论】:

天哪! 我该怎么做...显然您需要将参数添加到您的数据库管理器。我有一门完整的课程,可以传给你。但老实说,你为什么不使用现成的东西呢?检查Dapper,这是一个非常酷的库。 是的!但我不想使用图书馆请你给我上课吗? 【参考方案1】:

显然您需要将参数添加到您的DBmanager 类。它还缺少一些其他重要的方法。这是您可以使用的完整类。我在 web.config 中使用标准的 ConnectionStrings 部分,而不是 AppSettings 部分。你可以修改你的 web.config(推荐),或者修改这个类。

//Author: Racil Hilan
//You are free to modify and use this class in any project, personal or commercial,
//as long as you include this note. The author assumes no responsibility whatsoever
//for any damage that results from using this class, and does not guarantee in any way
//the suitability of this class for any purpose.
using System;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace DataLayer 
  /// <summary>Class that encapsulates a SQL Server database connection and CRUD operations.</summary>
  public class SQLServerDb : IDisposable 
    private DbConnection _con;

    /// <summary>Default constructor which uses the "DefaultConnection" connectionString.</summary>
    public SQLServerDb() : this("DefaultConnection")  

    /// <summary>Constructor which takes the connection string name.</summary>
    /// <param name="connectionStringName"></param>
    public SQLServerDb(string connectionStringName) 
      string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
      _con = new SqlConnection(connectionString);
    

    /// <summary>Executes a non-query command.</summary>
    /// <param name="command">The command to execute.</param>
    /// <returns>The count of records affected by the command.</returns>
    public int ExecuteNonQuery(DbCommand command) 
      int result = 0;
      if (command == null)
        throw new ArgumentException("Command cannot be null.");
      try 
        _con.Open();
        result = command.ExecuteNonQuery();
      
      finally 
        _con.Close();
      
      return result;
    

    /// <summary>Executes a command that returns a single scalar value.</summary>
    /// <param name="command">The command to execute.</param>
    /// <returns>The value returned by executing the command.</returns>
    public object ExecuteScalar(DbCommand command) 
      object result = null;
      if (command == null)
        throw new ArgumentException("Command cannot be null.");
      try 
        _con.Open();
        result = command.ExecuteScalar();
      
      finally 
        _con.Close();
      
      return result;
    

    /// <summary>Executes a command that returns a DataSet.</summary>
    /// <param name="command">The command to execute.</param>
    /// <returns>The DataSet returned by executing the ecommand.</returns>
    public DataSet ExecuteDataSet(DbCommand command) 
      DataSet ds = new DataSet();
      if (command == null)
        throw new ArgumentException("Command cannot be null.");
      try 
        DbDataAdapter ad = new SqlDataAdapter((SqlCommand)command);
        ad.Fill(ds);
      
      finally 
        _con.Close();
      
      return ds;
    

    /// <summary>Creates a command with the given parameters.</summary>
    /// <param name="commandText">The SQL query to execute.</param>
    /// <returns>The created command.</returns>
    public DbCommand GetSqlStringCommand(string commandText) 
      return GetCommand(commandText, CommandType.Text);
    

    /// <summary>Creates a command with the given parameters.</summary>
    /// <param name="commandText">The name of the stored procedure to execute.</param>
    /// <returns>The created command.</returns>
    public DbCommand GetStoredProcedureCommand(string commandText) 
      return GetCommand(commandText, CommandType.StoredProcedure);
    

    /// <summary>Creates a command with the given parameters.</summary>
    /// <param name="commandText">The name of the stored procedure to execute.</param>
    /// <returns>The created command.</returns>
    private DbCommand GetCommand(string commandText, CommandType commandType) 
      DbCommand command = _con.CreateCommand();
      command.CommandType = commandType;
      command.CommandText = commandText;
      return command;
    

    /// <summary>Adds an in parameter to a command.</summary>
    /// <param name="command">The SQL query to execute</param>
    /// <param name="name">The name of the parameter.</param>
    /// <param name="dbType">The type of the parameter.</param>
    /// <param name="value">The value of the parameter.</param>
    public void AddInParameter(DbCommand command, string name, DbType dbType, object value) 
      AddParameter(command, name, dbType, value, ParameterDirection.Input, 0);
    

    /// <summary>Adds an out parameter to a command.</summary>
    /// <param name="command">The SQL query to execute</param>
    /// <param name="name">The name of the parameter.</param>
    /// <param name="dbType">The type of the parameter.</param>
    /// <param name="size">The maximum size, in bytes, of the data within the column.</param>
    public void AddOutParameter(DbCommand command, string name, DbType dbType, int size) 
      AddParameter(command, name, dbType, null, ParameterDirection.Output, size);
    

    /// <summary>Adds a parameter to a command.</summary>
    /// <param name="command">The SQL query to execute</param>
    /// <param name="name">The name of the parameter.</param>
    /// <param name="dbType">The type of the parameter.</param>
    /// <param name="value">The value of the parameter.</param>
    /// <param name="direction">The direction for the parameter.</param>
    /// <param name="size">The maximum size, in bytes, of the data within the column.</param>
    private void AddParameter(DbCommand command, string name, DbType dbType, object value, ParameterDirection direction, int size) 
      var parameter = command.CreateParameter();
      parameter.ParameterName = name;
      parameter.DbType = dbType;
      parameter.Value = value ?? DBNull.Value;
      parameter.Direction = direction;
      if (size > 0)
        parameter.Size = size;
      command.Parameters.Add(parameter);
    

    public void Dispose() 
      if (_con != null) 
        _con.Dispose();
        _con = null;
      
    
  

您可以将它与您的示例一起使用,如下所示:

var db = new SQLServerDb();
string sql = @"INSERT INTO accounts(email, password, user_type) VALUES(@email, @password, @userType);";
DbCommand cmd = db.GetSqlStringCommand(sql);
db.AddInParameter(cmd, "@email", DbType.String, bll.email);
db.AddInParameter(cmd, "@password", DbType.String, bll.password);
db.AddInParameter(cmd, "@userType", DbType.Boolean, bll.userType);
DataRow dr = db.ExecuteDataSet(cmd).Tables[0].Rows[0];

要将其用于存储过程而不是查询,请使用GetStoredProcedureCommand() 而不是GetSqlStringCommand()

【讨论】:

感谢您的宝贵时间! 密码在字节数组中,因为我在存储之前对其进行了加密。 你不应该加密密码,你应该散列它们,并且散列是字符串。为此,请使用内置的 CreateHash()VerifyHashedPassword() 函数。永远不要尝试实现自己的安全性,始终使用知名库。 我正在使用md5加密并将其存储在二进制数据类型的数据库中。现在要改什么?数据库列类型二进制到 nvarchar ? 不,给varchar。哈希只有 ASCII 字符,所以你不需要 Unicode nvarchar

以上是关于asp.net 中第三层(数据访问层)的 Db Manager 类的主要内容,如果未能解决你的问题,请参考以下文章

asp.net中的三层架构是啥意思

ASP.NET MVC 的三层架构 + EF数据模型

ASP.NET MVC 的三层架构 + EF数据模型

asp.net中的三层架构是啥意思?mvc设计模式是啥?它们之间有关系吗?

在ASP.NET中,三层架构,Web ,BLL,DAL,Models这四个的引用关系是?

ASP.NET中MVC的理解