static void Main(string[] args)
{
SqlConnection sc = new SqlConnection("Data Source=pc3490ierf43;Initial Catalog=Persons;Integrated Security=True");
sc.Open();
SqlCommand command=new SqlCommand("Select Name from Persontable",sc);
SqlDataReader reader= command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0}", reader.GetString(0));
}
Console.ReadLine();
}
---------------------------------------------------------------------------------------------------------------------
** 2.code**
static void Main(string[] args)
{
using (SqlConnection sc = new SqlConnection("Data Source=pc3490ierf43;Initial Catalog=Persons;Integrated Security=True"))
{
sc.Open();
using (SqlCommand command = new SqlCommand("Select Name from Persontable", sc))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0}", reader.GetString(0));
}
}
}
Console.ReadLine();
}
----------------------------------------------------------------------------------------------------------------------------
First of all, I get the same output for both code blocks.
My question is how does the first example work since i haven't used the .Dispose() method and what dou you suggest should i stick with the using's or should i manage my connections manually?. I ve read that the using 's have the dispose integrated inside of them. I m just unsure sometimes when to use using when not. For instance in this code i would just use it for making a connection and the other constructros such as SqlCommand and SqlDataReader i wouldn't.