2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ACCESSにADO.NETでアクセスする場合のトランザクション制御 #3

Last updated at Posted at 2015-06-18

接続型の更新処理

二つのUPDATE文を発行する場合を例に示す。
トランザクション制御を行なわないと、二つ目のUPDATE文がエラーになっても一つ目のUPDATE文はROLLBACKされない。

トランザクション制御なしの更新

トランザクション制御なしの更新
OleDbCommand CMD = new OleDbCommand();
CMD.Connection = CONN;    // CONNはOleDbConnection。定義の記述を省略。
CONN.Open();

try
{
    CMD.CommandText = "UPDATE 部署テーブル xxx";      // 記述省略
    CMD.ExecuteNonQuery();

    CMD.CommandText = "UPDATE 従業員テーブル xxx";    // 記述省略
    CMD.ExecuteNonQuery();
}
catch (Exception ex)
{
    textBox.Text = "エラーが発生しました。" + ex.Message;
}
finally
{
    CONN.Close();
}

トランザクション制御ありの更新

トランザクション制御ありの更新
OleDbCommand CMD = new OleDbCommand();
CMD.Connection = CONN;    // CONNはOleDbConnection。記述を省略。
CONN.Open();

OleDbTransaction TRN = CONN.BeginTransaction(IsolationLevel.ReadCommitted);
CMD.Transaction = TRN;

try
{
    CMD.CommandText = "UPDATE 部署テーブル xxx";      // 記述省略
    CMD.ExecuteNonQuery();

    CMD.CommandText = "UPDATE 従業員テーブル xxx";    // 記述省略
    CMD.ExecuteNonQuery();

    TRN.Commit();
}
catch (Exception ex)
{
    TRN.Rollback();
    textBox.Text = "エラーが発生したのでロールバックしました。" + ex.Message;
}
finally
{
  CONN.Close();
}

参考:SqlTransaction.Rollback メソッド

ACCESSにADO.NETでアクセスする場合のトランザクション制御 #1
非接続型のトランザクション制御
・接続型のトランザクション制御
複数のDataTableの変更を同時にDBに反映する際のトランザクション制御
接続型、非接続型が混在した更新のトランザクション制御
トランザクション制御に関する分かり難いエラーメッセージ

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?