We need to use for SqlCommand or enough for SqlConnection and SqlDataReader

I took this code from msdn

string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"; using (SqlConnection conn = new SqlConnection(connString)) { SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers"; conn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1)); } } 

since you can see that there is no use for SqlCommand here, so what should it be?

+4
source share
2 answers

You need using for every object you create that implements IDisposable . This includes SqlCommand and SqlConnection .


There are very few exceptions to this rule. The main exceptions are WCF proxies. Due to a design flaw, their Dispose method can sometimes throw an exception. If you used the proxy server in the using statement, this second exception will result in the loss of the original exception.

+9
source

You are not using. The using statement MUST be used, but this is good practice and you MUST use it. This allows you to automatically delete objects using IDisposable.

http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx

Edited to add a link and remove inaccurate instructions because @John Saunders is right.

+3
source

Source: https://habr.com/ru/post/1301110/


All Articles