Information Technology Reference
In-Depth Information
{
SqlConnection
myConnection =
null
;
SqlCommand
mySqlCommand =
null
;
try
{
myConnection =
new
SqlConnection
(connString);
mySqlCommand =
new
SqlCommand
(commandString,
myConnection);
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
}
finally
{
if
(mySqlCommand !=
null
)
mySqlCommand.Dispose();
if
(myConnection !=
null
)
myConnection.Dispose();
}
}
One reason to just leave well enough alone is that you can easily get too
cute and try to build one
using
clause with
as
statements:
public void
ExecuteCommand(
string
connString,
string
commandString)
{
// Bad idea. Potential resource leak lurks!
SqlConnection
myConnection =
new
SqlConnection
(connString);
SqlCommand
mySqlCommand =
new
SqlCommand
(commandString,
myConnection);
using
(myConnection
as
IDisposable
)
using
(mySqlCommand
as
IDisposable
)
{
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
}
}
It looks cleaner, but it has a subtle bug. The SqlConnection object never
gets disposed if the SqlCommand() constructor throws an exception.