You are asking for safety, and that could be related from a resources viewpoint or from a database data viewpoint.
The using statement
The using statement is syntactic sugar for a try-catch-finally
statement where unmanaged resources are freed.
Do note that this has nothing to do with your database code, it only handles the IDisposable
objects, in your code the SQLConnection
and SQLCommand
.
You could choose to not write the using statement, but is so useful and I would advice you using the using
statement... And not only to database connections but for other unmanaged resources as well.
The SQLTransaction
A database transaction would be needed if there were more than one operation and you cared to make sure they behave in an atomic way (either all complete or nothing changes).
You can have database transactions directly in your SQL code or declared in your .net code using a SQLTransaction:
In your SQL code:
BEGIN TRANS myTrans
Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description');
Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description');
COMMIT TRANS myTrans
or declared in .NET:
try
{
command.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
command.ExecuteNonQuery();
command.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
command.ExecuteNonQuery();
// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}