0

I have this code for inserting data into a database. Before I commit, I want to be sure that the data is entered successfully, then commit else rollback both inserts.

try {
    statement one commit;
    statement two commit;
}
catch {
    error message
    statement 1 Rollback();
    statement 2 Rollback();
}
finally {
    if (con.State == Con.Open)
        con.Close();
}
Dovydas Šopa
  • 2,282
  • 8
  • 26
  • 34
alizee
  • 1
  • 1
  • 3
  • 2
    Your question is a bit unclear, and the title is confusing as 1) You're not creating a DB transaction in the psuedocode and 2) the statements aren't run in parallel. – stuartd Mar 08 '17 at 12:04
  • Put all your insert script inside the try {} because they aren't parallel run if the try fails it will just go to the 'catch', you are essentially saying "try inserting this data but if it fails catch it". – Neil Norris Mar 08 '17 at 12:27
  • Perhaps have a look at [Transactions in .net](http://stackoverflow.com/questions/224689/transactions-in-net) – stuartd Mar 08 '17 at 12:31

1 Answers1

0

You were very near to do this, you just have to put one commit statement after the two statements, if the code reached to that point, this mean that the none of the any throw an exception, so you can do the commit because you are sure the two statements has been executed successfully.

try   
{
    statement one;
    statement two;
    commit;
}
catch  
{
     error message
     statement 1 Rollback();
     statement 2 Rollback();
}
finally
{
     if (con.State == Con.Open)
          con.Close();
}
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131