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));
}
}
as you can see there is no using for the SqlCommand here, so, does it needs to be ?
"Not calling dispose on the command won't do anything too bad." True, but don't get used to it; it's only true for SqlCommand s. On the other hand, not disposing a SqlCeCommand , for example, will cause your mobile device to run out of memory quite fast.
SQL stands for Structured Query Language. SQL commands are the instructions used to communicate with a database to perform tasks, functions, and queries with data. SQL commands can be used to search the database and to do other functions like creating tables, adding data to tables, modifying data, and dropping tables.
You don't need the . Close() statement in either sample: it's handled by the . Dispose() call.
SqlCommand in C# allow the user to query and send the commands to the database. SQL command is specified by the SQL connection object. Two methods are used, ExecuteReader method for results of query and ExecuteNonQuery for insert, Update, and delete commands. It is the method that is best for the different commands.
You need a using
for every object you create that implements IDisposable
. That includes the SqlCommand
and the SqlConnection
.
There are very few exceptions to this rule. The main exception is WCF client proxies. Due to a design flaw, their Dispose
method can sometimes throw an exception. If you used the proxy in a using
statement, this second exception would cause you to lose the original exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With