简体   繁体   English

我需要关闭数据读取器吗

[英]Do I need to close the datareader

I have this simple function that takes care of all the queries: 我有一个简单的功能,可以处理所有查询:

DataTable ReadIt(string query, params MySqlParameter[] sqlParams)
{
    DataTable dt = new DataTable();

    using(MySqlConnection myConnection = new MySqlConnection(sConnection))
    {
        myConnection.Open();
        MySqlCommand myCommand = myConnection.CreateCommand();
        myCommand.CommandText = query;
        foreach (var p in sqlParams)
        {
            myCommand.Parameters.Add(p);
        }
        MySqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
        dt.Load(myReader);
        myReader.Close();
    }

    return dt;
}

Do I need to put myReader.Close(); 我需要放myReader.Close();myReader.Close(); after loading the data to the datatable or does the reader closes automatically after using ? 将数据加载到数据表后还是using后读取器自动关闭?

You don't know (or at least you shouldn't know) what resources the DataReader is holding. 您不知道(或至少您不应该知道)DataReader拥有什么资源。
On the other side every disposable object should be disposed because, in the disposing code, the object has the opportunity to release, as soon as possible, the resources used. 另一方面,应该处理每个可丢弃对象,因为在处理代码中,对象有机会尽快释放所使用的资源。
So also your MySqlDataReader should follow the same pattern used for the MySqlConnection and also for the MySqlCommand. 因此,您的MySqlDataReader也应遵循用于MySqlConnection和MySqlCommand的相同模式。 The Using Statement is your friend 使用声明是您的朋友

using(MySqlConnection myConnection = new MySqlConnection(sConnection))
using(MySqlCommand myCommand = myConnection.CreateCommand())
{
    myConnection.Open();
    myCommand.CommandText = query;
    foreach (var p in sqlParams)
        myCommand.Parameters.Add(p);
    using(MySqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection))
    {
        dt.Load(myReader);
    }
}

DataTable.Load will automatically close the reader if there are no more result grids. 如果没有更多的结果网格, DataTable.Load将自动关闭阅读器。 That is a bit hit and miss for my liking; 我的喜好有点错过。 I'd use using : 我会使用using

using(var myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)) {
    dt.Load(myReader);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM