哪种模式更适合 SqlConnection 对象?

发布于 2024-09-12 10:48:10 字数 1433 浏览 3 评论 0原文

哪种模式更适合 SqlConnection 对象?性能上哪个更好? 你们提供其他模式吗?

class DataAccess1 : IDisposable
{
    private SqlConnection connection;

    public DataAccess1(string connectionString)
    {
        connection = new SqlConnection(connectionString);
    }

    public void Execute(string query)
    {
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = query;
            command.CommandType = CommandType.Text;
            // ...

            command.Connection.Open();
            command.ExecuteNonQuery();
            command.Connection.Close();
        }
    }

    public void Dispose()
    {
        connection.Dispose();
    }
}

VS

class DataAccess2 : IDisposable
{
    private string connectionString;

    public DataAccess2(string connectionString)
    {
        this.connectionString = connectionString;
    }

    public void Execute(string query)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = connection.CreateCommand();
            command.CommandText = query;
            command.CommandType = CommandType.Text;
            // ...

            command.Connection.Open();
            command.ExecuteNonQuery();
            command.Connection.Close();
        }
    }

    public void Dispose()
    {            
    }
}

Which pattern is better for SqlConnection object? Which is better in performance?
Do you offer any other pattern?

class DataAccess1 : IDisposable
{
    private SqlConnection connection;

    public DataAccess1(string connectionString)
    {
        connection = new SqlConnection(connectionString);
    }

    public void Execute(string query)
    {
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = query;
            command.CommandType = CommandType.Text;
            // ...

            command.Connection.Open();
            command.ExecuteNonQuery();
            command.Connection.Close();
        }
    }

    public void Dispose()
    {
        connection.Dispose();
    }
}

VS

class DataAccess2 : IDisposable
{
    private string connectionString;

    public DataAccess2(string connectionString)
    {
        this.connectionString = connectionString;
    }

    public void Execute(string query)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = connection.CreateCommand();
            command.CommandText = query;
            command.CommandType = CommandType.Text;
            // ...

            command.Connection.Open();
            command.ExecuteNonQuery();
            command.Connection.Close();
        }
    }

    public void Dispose()
    {            
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

苏璃陌 2024-09-19 10:48:10

没有真正的方法来回答这个问题。简短而规范的答案是,连接应该在工作单元的生命周期内保持活动状态。因为我们无法知道如何使用 DataAccess(它是否在您的应用程序的生命周期中存在,或者您是否在执行某些操作时实例化它并处置它?),因此不可能给出具体的信息回答。

话虽这么说,我会推荐第一种模式,但根据需要实例化并处置您的 DataAccess 对象;不要将其保留超过必要的时间。

There's no real way to answer this question. The short, canonical answer is that the connection should stay alive for the lifetime of your unit of work. Because we have no way of knowing how DataAccess is used (does it exist for the lifetime of your application, or do you instantiate it and dispose it whenever you do something?), it's impossible to give a concrete answer.

That being said, I would recommend the first pattern, but instantiate and dispose of your DataAccess object as needed; don't keep it around longer than necessary.

寂寞清仓 2024-09-19 10:48:10

建议使用DataAccess2。但这是个人喜好。有些人甚至可能建议您的类是静态的。很难说其中一个比另一个性能更好。您正走在 IDisposable 的道路上,这很棒。

我很乐意阅读并维护您问题中上面显示的两种样式。

考虑让您的 DAL 也能够从 .config 读取连接字符串,而不是专门允许在构造函数中传递值。

public DataAccess2(string connStr)
{
    this.connectionString = connStr;
}
public DataAccess2()
{
    this.connectionString = 
            ConfigurationManager.ConnectionStrings["foo"].ConnectionString;
}

也可以考虑将 SqlCommand 包装在 using 中。

using (var conn = new SqlConnection(connectionString))
{
    using(var cmd = conn.CreateCommand())
    {

    }
}

Suggest going with DataAccess2. It's a personal preference though. Some might even suggest your class be static. It'd be difficult to say that one is more performant than the other. You're on the path of IDisposable, which is great.

I'd be happy to read and maintain both styles shown above in your question.

Consider having your DAL be able to read the connection string from a .config as well, rather than exclusively allowing the value to be passed in the constructor.

public DataAccess2(string connStr)
{
    this.connectionString = connStr;
}
public DataAccess2()
{
    this.connectionString = 
            ConfigurationManager.ConnectionStrings["foo"].ConnectionString;
}

Consider wrapping your SqlCommand in a using as well.

using (var conn = new SqlConnection(connectionString))
{
    using(var cmd = conn.CreateCommand())
    {

    }
}
你是暖光i 2024-09-19 10:48:10

如果您进行并发调用,第一个将导致错误。
第二个将确保您对每个命令使用干净的连接,从而建立更多的连接。

我同意上面的说法,这取决于使用场景,为了解决与第一个相关的问题,我有一个需要使用这种模式的包装器,所以我设置了一个字段值布尔值来显示正在执行命令已经连接上,然后“排队”下一个命令以供执行。

当然,在某些情况下您可能更喜欢使用多个连接......

The first will result in errors if you make concurrent calls.
The second will ensure you use a clean connection for each command resulting in more connections being made.

I agree with the statements above that it depends on the scenario for use, to get over the problem related to the first I have a wrapper that needs to use such a pattern so I set a field value boolean to show that a command is being executed on the connection already then "queue" the next command for execution.

There will of course be situations where you may prefer to use multiple connections ...

笑看君怀她人 2024-09-19 10:48:10

我认为这取决于您的 DataAccess 对象的使用方式,如果它在“using”子句中使用,那么连接保证在完成后被释放。

但一般来说,我更喜欢第二种模式,因为 sql 连接是在 Execute 方法中创建和处置的,因此当您忘记处置 DataAccess 对象时,它不太可能保持打开状态。

考虑到 sql 连接可能是一种稀缺资源,我认为应该尽一切努力确保它们不被浪费。

I think it depends on how your DataAccess object is intended to be used, if it's used within a 'using' clause then the connection is guaranteed to be disposed of after it's done.

But in general I prefer the second pattern as the sql connection is created and disposed of within the Execute method so it's less likely to be left open when you forget to dispose of your DataAccess object.

Considering that sql connection can be a scarse resource I think every attempt should be made to ensure that they're not wasted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文