打开SqlDataReader时是否有任何方法可以避免使用嵌套?

时间:2012-02-24 07:10:52

标签: c# .net sqldatareader

没什么大不了的,但为了整洁,有没有办法“创建并打开”SqlConnection

我天真地写了这段代码:

using (var strConnection = new SqlConnection(sourceConnection))
using (var strCommand = new SqlCommand(query, strConnection))
using (var reader = strCommand.ExecuteReader())
{
    ...
}

第3行当然失败,因为连接未打开 是否有一种巧妙的方法来避免打开连接引入的嵌套?

using (var strConnection = new SqlConnection(sourceConnection))
{
    strConnection.Open();
    using (var strCommand = new SqlCommand(query, strConnection))
    using (var reader = strCommand.ExecuteReader())
    {
        ...
    }
}

2 个答案:

答案 0 :(得分:1)

这样的事情:

class SqlHelper : IDisposable
{
    public SqlHelper(string connectionString, string query) { ... }

    public SqlConnection Connection { get; set; }
    public SqlCommand Command { get; set; }

    // SQL querying logic here
    public void Execute() { ... }

    /** IDisposable implementation **/
}

并在您的代码中

using (SqlHelper sql = new SqlHelper(sourceConnection, query)) 
{
    var reader = sql.Execute();
    ...
}

答案 1 :(得分:1)

好问题,我的想法是SqlConnection的扩展方法。

检查一下:

public static class SqlExtensions {
    public static SqlConnection OpenAndReturn(this SqlConnection con) {
        try {
            con.Open();
            return con;
        } catch {
            if(con != null)
                con.Dispose();
            throw;
        }
    }
}

用法:

using(var strConnection = new SqlConnection("CONNECTION").OpenAndReturn()) 
using(var strCommand = new SqlCommand("QUERY", strConnection))
using(var reader = strCommand.ExecuteReader()) {
    //...       
}