What is using connection in the code
What is the purpose of using (connection)
in the code - please explain me
static void HasRows(SqlConnection connection)
{
using (connection)/// what is this line
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();
SqlDataReader reader = c开发者_如何学Goommand.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();
}
}
using (connection){
connection.Open();
}
makes sure that connection
is closed when the application is done using it.
similar to a Try Catch
.
try{
connection.Open();
}
catch{
}
finally{
connection.Dispose();
}
Disposing of the connection is another way of saying closing a connection. An open connection can leak memory and if you have too many it can slow down or freeze up whatever you are connecting to.
the using
function closes the connection even after you return something from the class you are in. same as the try catch
. it always closes the connection no matter what happens inside the brackets. even if there is an exception that breaks out of the class/application the connection still gets closed
Using
Quote from site:
The using
statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable
interface. This interface provides the Dispose
method, which should release the object's resources.
I would probably re-write the method to something like the following:
static void HasRows(string connectionString)
{
using (var connection = new SqlConnection(connectionString))
using(var command = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;",
connection))
{
connection.Open();
using (var 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.");
}
}
}
}
In your original implementation the caller could be at the receiving end of an ObjectDisposedException
exception, because the SqlConnection is passed in as a parameter.
精彩评论