How to use transctions

2006-08-28
2013-04-15
  • Hello english is not my native language so please bare with me.
    I’m trying to do a large number of inserts, but the previous insert depends on the
    success of the previous insert,  if one insert fails when need to rollback to the previous state. I’m using C# (Visual Studio Express).
    I only need a code sample, ps: my brain can’t process vb.
    Thanks in advanced.

     
    • Haven't tested it, but something like this should work.  oCn is an open connection to your SQLite DB.

      public static void RunSQL(string strSQL)
      {

          SQLiteCommand command = new SQLiteCommand(strSQL, oCn);
          command.ExecuteNonQuery();
          command.Dispose();
      }

      public void SetOfInserts()
      {
          try
          {
              RunSQL("BEGIN;");
              RunSQL("INSERT INTO TABLE VALUES ('ASDF');");
              RunSQL("INSERT INTO TABLE VALUES ('QWER');");
              RunSQL("INSERT INTO TABLE VALUES ('ASDF');");
              RunSQL("COMMIT;");
          }
          catch (Exception ex)
          {
              RunSQL("ROLLBACK;");
              MessageBox.Show(ex.Description);
          }
      }