C#:
SqlConnection connection = null;
SqlCommand command = null;
try
{
connection = new SqlConnection();
// Some exception handling should be added here to make sure
//the connection string isn't null or empty.
connection.ConnectionString =
ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString;
// Allocation the connection
connection.Open();
command = connection.CreateCommand();
// Use and execute this command...
}
catch (SqlException _exception)
{
Debug.WriteLine(_exception.ToString());
throw;
}
finally
{
command.Dispose();
connection.Dispose();
}
VB.NET:
Dim connection As SqlConnection = Nothing
Dim command As SqlCommand = Nothing
Try
connection = New SqlConnection()
' Some exception handling should be added here to make sure
' the connection string isn't null or empty.
connection.ConnectionString = ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString
' Allocation the connection
connection.Open()
' Use and execute this command...
command = connection.CreateCommand()
Catch _exception As SqlException
Debug.WriteLine(_exception.ToString())
Throw
Finally
command.Dispose()
connection.Dispose()
End Try
The "using" statement (RECOMMENDED):
The using statement creates a scope for your disposable variable, then when you go out of scope, it *automatically* calls .Dispose() for you (even if an exception occurs).
C#:
try
{
using (SqlConnection connection = new SqlConnection())
{
// Some exception handling should be added here to make sure
// the connection string isn't null or empty.
connection.ConnectionString = ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString;
// Allocation the connection
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
// Use and execute this command...
}
}
}
catch (SqlException _exception)
{
Debug.WriteLine(_exception.ToString());
throw;
}
VB.NET:
Try
Using connection As New SqlConnection
' Some exception handling should be added here to make sure
' the connection string isn't null or empty.
connection.ConnectionString = _
ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString
' Allocation the connection
connection.Open()
Using command As SqlCommand = connection.CreateCommand()
' Use and execute this command...
End Using
End Using
Catch _exception As SqlException
Debug.WriteLine(_exception.ToString())
Throw
End Try