I usually write my DataReader
code like this:
try
{
dr = cmd.ExecuteReader(CommandBehavior.SingleResult);
while (dr.Read())
{
// Do stuff
}
}
finally
{
if (dr != null) { dr.Close(); }
}
Is it safe to replace the try
and finally
with just a using
block around the DataReader
's creation? The reason I wonder is because in all the Microsoft examples I've seen they use a using for the connection but always explicitly call Close()
on the DataReader
.
Heres's an example from
Retrieving Data Using a DataReader (ADO.NET):
static void HasRows(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…