我可以处置 DataTable 并在以后仍然使用其数据吗?

发布于 2024-10-20 12:58:21 字数 2173 浏览 2 评论 0原文

ADO.NET 菜鸟问题:我可以执行以下操作吗?

  1. 以某种方式检索数据表。
  2. 处理掉它。
  3. 还是用它的数据吧。 (但不将其发送回数据库,或请求数据库更新它。)

我有以下函数,它由我的 Web 服务中的每个 WebMethod 间接调用:

public static DataTable GetDataTable(string cmdText, SqlParameter[] parameters)
{
    // Read the connection string from the web.config file.
    Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/WSProveedores");
    ConnectionStringSettings connectionString = configuration.ConnectionStrings.ConnectionStrings["..."];

    SqlConnection connection = null;
    SqlCommand command = null;
    SqlParameterCollection parameterCollection = null;
    SqlDataAdapter dataAdapter = null;
    DataTable dataTable = null;

    try
    {
        // Open a connection to the database.
        connection = new SqlConnection(connectionString.ConnectionString);
        connection.Open();

        // Specify the stored procedure call and its parameters.
        command = new SqlCommand(cmdText, connection);
        command.CommandType = CommandType.StoredProcedure;
        parameterCollection = command.Parameters;
        foreach (SqlParameter parameter in parameters)
            parameterCollection.Add(parameter);

        // Execute the stored procedure and retrieve the results in a table.
        dataAdapter = new SqlDataAdapter(command);
        dataTable = new DataTable();
        dataAdapter.Fill(dataTable);
    }
    finally
    {
        if (connection != null)
        {
            if (command != null)
            {
                if (dataAdapter != null)
                {
                    // Here the DataTable gets disposed.
                    if (dataTable != null)
                        dataTable.Dispose();
                    dataAdapter.Dispose();
                }

                parameterCollection.Clear();
                command.Dispose();
            }

            if (connection.State != ConnectionState.Closed)
                connection.Close();
            connection.Dispose();
        }
    }

    // However, I still return the DataTable
    // as if nothing had happened.
    return dataTable;
}

Noob ADO.NET question: Can I do the following?

  1. Retrieve a DataTable somehow.
  2. Dispose it.
  3. Still use its data. (But not send it back to the database, or request the database to update it.)

I have the following function, which is indirectly called by every WebMethod in a Web Service of mine:

public static DataTable GetDataTable(string cmdText, SqlParameter[] parameters)
{
    // Read the connection string from the web.config file.
    Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/WSProveedores");
    ConnectionStringSettings connectionString = configuration.ConnectionStrings.ConnectionStrings["..."];

    SqlConnection connection = null;
    SqlCommand command = null;
    SqlParameterCollection parameterCollection = null;
    SqlDataAdapter dataAdapter = null;
    DataTable dataTable = null;

    try
    {
        // Open a connection to the database.
        connection = new SqlConnection(connectionString.ConnectionString);
        connection.Open();

        // Specify the stored procedure call and its parameters.
        command = new SqlCommand(cmdText, connection);
        command.CommandType = CommandType.StoredProcedure;
        parameterCollection = command.Parameters;
        foreach (SqlParameter parameter in parameters)
            parameterCollection.Add(parameter);

        // Execute the stored procedure and retrieve the results in a table.
        dataAdapter = new SqlDataAdapter(command);
        dataTable = new DataTable();
        dataAdapter.Fill(dataTable);
    }
    finally
    {
        if (connection != null)
        {
            if (command != null)
            {
                if (dataAdapter != null)
                {
                    // Here the DataTable gets disposed.
                    if (dataTable != null)
                        dataTable.Dispose();
                    dataAdapter.Dispose();
                }

                parameterCollection.Clear();
                command.Dispose();
            }

            if (connection.State != ConnectionState.Closed)
                connection.Close();
            connection.Dispose();
        }
    }

    // However, I still return the DataTable
    // as if nothing had happened.
    return dataTable;
}

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

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

发布评论

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

评论(2

掌心的温暖 2024-10-27 12:58:21

一般规则是处置任何实现了 IDisposable 的东西,无论它是否“需要”。让您免于“需要”而您却没有想到要丢弃的情况。

一旦对对象调用了 Dispose,就不应再使用它。时期。它违反了整个 Dispose 的概念。

这就是为什么您不应该对从方法返回的对象调用 Dispose。让调用者在处理完对象后调用 Dispose。


顺便说一句,你的代码可以更简单。更多类似这样的:

using (SqlConnection connection = new SqlConnection(connectionString.ConnectionString))
{
    connection.Open();

    using (SqlCommand command = new SqlCommand(cmdText, connection))
    {
        //...
        using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
        {
            DataTable dataTable = new DataTable();
            dataAdapter.Fill(dataTable);
            return dataTable;
        }
    }
}

The general rule is to Dispose anything that implements IDisposable, whether it "needs it" or not. Saves you from the times when it "needs it" and you didn't think to Dispose.

Once you've called Dispose on an object, you shouldn't use it anymore. Period. It violates the entire concept of Dispose.

This is why you shouldn't call Dispose on an object that you are returning from a method. Leave it up to the caller to call Dispose when they're done with the object.


BTW, your code could be simpler. More like this:

using (SqlConnection connection = new SqlConnection(connectionString.ConnectionString))
{
    connection.Open();

    using (SqlCommand command = new SqlCommand(cmdText, connection))
    {
        //...
        using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
        {
            DataTable dataTable = new DataTable();
            dataAdapter.Fill(dataTable);
            return dataTable;
        }
    }
}
天煞孤星 2024-10-27 12:58:21

好吧,你不能鱼与熊掌兼得:)

当然,关闭连接等等,但是为什么你需要处置桌子呢?那没有必要。只需按原样返回即可。

否则你会处于这样的境地:将表复制到其他内容,然后返回它?例如,如果您使用 ORM 并将数据映射到对象,然后返回对象,那么这是有意义的,但如果您不使用 ORM,则直接使用表/数据集。

Well, you can't have your cake and eat it :)

Close the connection and so on, sure, but why do you need to dispose the table? That's not necessary. Just return it as-is.

Otherwise you'd be in a position where you... copy the table to something else and then return that instead? If you were using a ORM for example and mapping data to objects and then returning the objects this would make sense, but if you're not then just use the table/dataset directly.

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