Will putting a “using” statement around a DataReader close it?

后端 未结 4 1448
栀梦
栀梦 2020-12-18 17:52

I usually write my DataReader code like this:

try
{
    dr = cmd.ExecuteReader(CommandBehavior.SingleResult);
    while (dr.Read())
    {
               


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 18:43

    Unlike the example here, my practice has been to employ a using block for the connection, the command and the reader. Note that you can stack nested using blocks to lower the indentation cost.

    static void HasRows(SqlConnection connection)
    {
        using (connection)
        using (SqlCommand command = new SqlCommand(
        "SELECT CategoryID, CategoryName FROM Categories;",
        connection))
        {
            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
                            reader.GetString(1));
                    }
                }
                else
                {
                    Console.WriteLine("No rows found.");
                }
                reader.Close();
            }   
        }
    }
    

提交回复
热议问题