哪种模式更适合 SqlConnection 对象? [英] Which pattern is better for SqlConnection object?

查看:38
本文介绍了哪种模式更适合 SqlConnection 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()
    {            
    }
}

推荐答案

建议使用 DataAccess2.不过这是个人喜好.有些人甚至可能建议您的类是 static.很难说一个比另一个更高效.您正在IDisposable 的道路上,这很棒.

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.

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

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;
}

考虑将您的 SqlCommand 包装在 using 中.

Consider wrapping your SqlCommand in a using as well.

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

    }
}

这篇关于哪种模式更适合 SqlConnection 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆