How to close the datareader

Total Post:154

Points:1086
 1169  View(s)
Ratings:
Rate this:
this is a 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;
}

I want to myReader.Close(); afeter loading data to datatable

  1. Post:194

    Points:1396
    Re: How to close the datareader

    try this code:

    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);
                }
            }

      Modified On Apr-05-2018 06:28:56 AM

Answer