ADO.NET数据访问层

时间:2015-11-06 08:32:33

标签: c# sql .net ado.net

我维护一个现有的C#应用​​程序,该应用程序使用经典的ADO.NET作为数据访问技术。现有代码创建了SqlConnectionSqlCommand个对象的新实例 EVERY 单次需要与数据库进行一些交互。为了简单起见,我写了一个小类来简化这个过程来预测代码重复,但我不是ADO.NET的专家所以我想问一下你是否可以查看我的代码并告诉我是否错过了任何ADO .NET最佳实践,或者下面的代码可能会对DB操作产生负面影响:

using System;
using System.Data;
using System.Data.SqlClient;

namespace MyApp.DataAccess
{
    public class DataAccessLayer : IDisposable
    {
        private SqlConnection _connection = new SqlConnection();
        private SqlCommand _command = new SqlCommand();

        public string ConnectionString 
        {
            get { return DBConfig.ConnectionString; }
        }

        public SqlCommand Command 
        {
            get { return _command; }
            set { _command = value; }
        }

        public SqlConnection SQLConnection 
        {
            get
            {
                if(_connection == null || _connection.State == ConnectionState.Closed)
                {
                    _connection = new SqlConnection(ConnectionString);
                    _connection.Open();
                }
                return _connection;
            }
        }

        public void SetCommand(string commandText,CommandType commandType)
        {
            _command = new SqlCommand(commandText, SQLConnection);
            _command.CommandType = commandType;
        }

        public void Dispose()
        {
            if (_connection != null)
                _connection.Dispose();

            if (_command != null)
                _command.Dispose();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

正如蒂姆解释的那样,我宁愿使用using语句对此进行编码。这将自动关闭并处置您的SqlConnection实例。

在MSDN页面中查看有关SqlConnection class

的示例
using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        // Do work here; connection closed on following line.
    }


而且model_dialog解释说,也是正确的。 如果您在Open类上调用SqlConnection方法,框架将无需真正打开新连接。

相反,它将检查连接池中是否已存在适当的连接。它通过检查连接字符串来完成此操作。如果找到合适的连接,连接池将返回此连接,几乎不会影响性能。可以这么说,连接池是SqlConnections的一个捕获组件。

请点击此处了解详情:SQL Server Connection Pooling (ADO.NET)