Kobarin's Development Blog

C#やASP.NET、公開APIなどについての記録です。

SqlTransactionの基本コード

using (SqlConnection cn = new SqlConnection([接続文字列]))
{
  using (SqlCommand cmd = cn.CreateCommand())
  {
    cn.Open();
    
    SqlTransaction tran = cn.BeginTransaction();
    
    try
    {
      cmd.Transaction = tran;
      
      cmd.CommandText = @"insert into Table1(Field1) values ('あいうえお')";
      cmd.ExecuteNonQuery();

      cmd.CommandText = @"insert into Table1(Field1) values ('かきくけこ')";
      cmd.ExecuteNonQuery();

      tran.Commit();
    }
    catch (Exception ex)
    {
      tran.Rollback();
    }

    cn.Close();
  }
}