HOW TO CLOSE THE DATAREADER

Manoj Bhatt

Total Post:154

Points:1086
Posted by  Manoj Bhatt
 911  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. Kamlakar Singh

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

                }

            }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!