I have following with two using block:
using (SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "query...";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@param", "paramValue");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Is it enought to make this query safety or is it require to declare a transaction like in this post?
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-finallystatement where unmanaged resources are freed.Do note that this has nothing to do with your database code, it only handles the
IDisposableobjects, in your code theSQLConnectionandSQLCommand.You could choose to not write the using statement, but is so useful and I would advice you using the
usingstatement... 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:
or declared in .NET: