Skip to main content

This version of the product is no longer supported, and this documentation is no longer updated regularly. See the latest version of this content.Opens in a new tab

Transactions

Use CacheTransaction to wrap database operations in transactions. CacheTransaction supports the BeginTransaction, Commit, and Rollback methods which, respectively, begin, commit and rollback a transaction.

The following code invokes InsertContact twice. It wraps the calls in a transaction to ensure that the pair of inserts are atomic. Both insertions are rolled back if an exception is thrown in either one.


CacheTransaction trans = null;
try
{
   CacheConnection cnCache = new CacheConnection(conStr);
   cnCache.Open();
   
   trans = cnCache.BeginTransaction();
   InsertContact(cnCache, trans, "Smith,Fred", "Personal");
   InsertContact(cnCache, trans, "Smith,Linda", "Busines");  
   trans.Commit();
}
catch(Exception e)
{
 trans.Rollback();
 Console.WriteLine("Exception: {0}", e.Message);
}        

Here is the InsertContact method called by the above code. Note that the CacheCommand constructor takes the CacheTransaction instance as an argument.


public int InsertContact(CacheConnection cnCache, CacheTransaction trans, 
                                                      string name, string type)
{
  string sql = "Insert into Provider.Contact(Name,ContactType) Values(?,?)";
  CacheCommand command = new CacheCommand(sql, cnCache, trans);

  CacheParameter name_param = new CacheParameter();
  name_param.CacheDbType = CacheDbType.NVarChar;
  name_param.ParameterName = "Name";
  name_param.Direction = ParameterDirection.Input;
  name_param.Value = name;

  CacheParameter type_param = new CacheParameter();
  type_param.CacheDbType = CacheDbType.NVarChar;
  type_param.ParameterName = "ContactType";
  type_param.Direction = ParameterDirection.Input;
  type_param.Value = type;

  command.Parameters.Add(name_param);
  command.Parameters.Add(type_param);
 
  int rows = command.ExecuteNonQuery();

  return rows;
} 

FeedbackOpens in a new tab