15.8.3 Executing a transaction

This example inserts data 1 to the ex table:

using System;
using System.Data;
using Hitachi.HiRDB;

namespace test_C
{
   class Sample
   {
       [STAThread]
       static void Main(string[] args)
       {
           // Create a Connection object
           HiRDBConnection cn = new HiRDBConnection("dsn=pc;");

           // Connect to the database
           cn.Open();

           // Create a Transaction object
           HiRDBTransaction tran;
           // Start of transaction
           tran = cn.BeginTransaction(IsolationLevel.ReadCommitted);  ..1
           // Create a Command object
           HiRDBCommand cm = new HiRDBCommand();
           cm.Connection = cn;
           cm.Transaction = tran;
           try
           {
               // Insert data in the table
               cm.CommandText = "insert into ex values (1)";
               cm.ExecuteNonQuery();

               // Transaction was successful
               tran.Commit();  .........................................2

               // Disconnect from the database
               cn.Close();
           }
           catch (HiRDBException ex)
           {
               // Transaction failed
               tran.Rollback();  .......................................3

               Console.WriteLine(ex);
           }
           catch (System.Exception ex)
           {
               // Transaction failed
               tran.Rollback();  .......................................3

               Console.WriteLine(ex);
           }
       }
   }
}

Explanation
  1. To start a transaction, use the BeginTransaction method.
  2. To complete the transaction, call the Commit method.
  3. To restore, call the Rollback method.