简体   繁体   中英

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(); after loading the data to the datatable or does the reader closes automatically after using ?

You don't know (or at least you shouldn't know) what resources the DataReader is holding.
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. 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. That is a bit hit and miss for my liking; I'd use using :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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