0

Is it necessary to put a Transaction around Manual SQL commands in c#?

I have the Situation where I have a Long running command which should either do it all or nothing at all in essence. with Manual C# SQL Connections (thus not using entityframework) I'm not sure if I Need to put a Transaction around it to achieve this behaviour or If the commands effects automatically don't occur if any error Pops up during the commands execution.

using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
    connection.Open();
    SqlCommand command = new SqlCommand();
    command.Connection = connection;
    command.CommandTimeout = 900;   // Wait 15 minutes before a timeout
    command.CommandText = "INSERT ......";
    command.ExecuteNonQuery();
}
Mohit S
  • 13,723
  • 6
  • 34
  • 69
Thomas
  • 2,886
  • 3
  • 34
  • 78

1 Answers1

1

Each individual statement is already atomic so you don't need a transaction.

Sql databases are - most of them at least - acid compliant, meaning that they gurantee Atomicity Consistency Isolation Durability When individual statements are executed.

Adding a transaction can make many statements behave as one acid compliant statement, but you only have one statement and it is completely redundant to wrap it in a transaction.

faester
  • 14,886
  • 5
  • 45
  • 56