成语使用SqlDataReader的作为资源 [英] Idiom for using SqlDataReader as a resource

查看:97
本文介绍了成语使用SqlDataReader的作为资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从<一个继href="http://stackoverflow.com/questions/1058591/net-sqlconnection-class-connection-pooling-and-reconnection-logic">this的问题,我发现自己一遍又一遍写下面的code:

Following on from this question, I find myself writing the following code over and over again:

SqlCommand command = new SqlCommand();
// Code to initialize command with what we want to do
using (SqlConnection connection = openConnection())
{
    command.Connection = connection;
    using (SqlDataReader dataReader = thisCommand.ExecuteReader())
    {
        while (dataReader.Read())
        {
            // Do stuff with results
        }
    }
}

这是相当繁琐不得不窝在两个using语句。有没有办法来的告诉的SqlDataReader的,它拥有的命令,告诉命令,它拥有的连接?

It's rather tedious to have to nest the two using statements. Is there a way to tell SqlDataReader that it owns the command, and tell the command that it owns the connection?

如果有这样做的话,我可以写一个辅助方法,它可以被称为像这样的一种方式:

If there was a way of doing that then I could write a helper method which could be called like so:

// buildAndExecuteCommand opens the connection, initializes the command
// with the connection and returns the SqlDataReader object. Dispose of the
// SqlDataReader to dispose of all resources that were acquired
using(SqlDataReader reader = buildAndExecuteCommand(...))
{
    // Do stuff with reader
}

或者我必须硬着头皮写我自己的包装上SqlDataReader的?

Or do I have to bite the bullet and write my own wrapper over SqlDataReader?

推荐答案

有一件事情是写它做了处置你,回调与每个结果代表的方法。例如:

One thing would be to write a method which did the disposal for you, calling back into a delegate with each result. For example:

using (SqlConnection connection = openConnection())
{
    command.Connection = connection;
    ExecuteReaderWithCommand(command, reader =>
    {
        // Do stuff with the result here.
    });
}

然后ExecuteReaderWithCommand会是这样的:

Then ExecuteReaderWithCommand would be something like:

public static void ExecuteReaderWithCommand(SqlCommand command,
    Action<SqlDataReader> action)
{
    using (SqlDataReader dataReader = thisCommand.ExecuteReader())
    {
        while (reader.Read())
        {
            action(reader);
        }
    }
}

您可以做这个,如果你想在的SqlCommand 的扩展方法。哎呀,你可以去城里,并使其为你打开的连接,如果你想和......更可以抽象掉的想法开/使用/关闭,就更好了。

You could make this an extension method on SqlCommand if you wanted to. Heck, you could go to town and make it open the connection for you as well if you wanted... the more you can abstract away the idea of "open / use / close", the better.

这篇关于成语使用SqlDataReader的作为资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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