6
Reply

How can we force the connection object to close after my datareader is closed ?

    user using() to free the memory allocated for resource .

    We can use "CommandBehaviour.CloseConnection" Like as :SqlCommand cmd = new SqlCommand("SELECT * FROM EMPLOYEE", con);con.Open();SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);while (reader.Read()){int weight = reader.GetInt32(0); // Weight intstring name = reader.GetString(1); // Name stringstring breed = reader.GetString(2); // Breed string//// Write the values read from the database to the screen.//Response.Write(weight.ToString() + name + breed);}reader.Close();

    1.we can use using() function it automatically close the connection after executing the query 2 .cmd.ExecuteReader(CommandBehavior.CloseConnection)

    There are 2 ways through which we can achieve this: (01.) Through "using()". (02.) Through passing "CommandBehavior.CloseConnection" as parameter to command object "ExecuteReader()"

    Using CommandBehaviour we can do objcommand.ExecuteReader(CommandBehaviour.ClossConnection)

    Command method Executereader takes a parameter called as CommandBehavior wherein we can specify saying close connection automatically after the Datareader is close. pobjDataReader = pobjCommand.ExecuteReader(CommandBehavior.CloseConnection)