0
1

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でアクセスする場合のトランザクション制御 #2

Last updated at Posted at 2015-06-18

非接続型の更新処理

DBからDataTableへの読み出し

DBからDataTableへの読み出し
OleDbConnection CONN = new OleDbConnection();
CONN.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.xxxx";    // 記述省略

String sql = "SELECT 名前, 年齢 FROM 従業員;
OleDbDataAdapter DA = new OleDbDataAdapter(sql, CONN);
DataTable DT = new DataTable();
DT.TableName = "従業員DT";
DA.Fill(DT);

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

トランザクション制御なしの更新
OleDbCommandBuilder CB = new OleDbCommandBuilder(DA);
try
{
    DA.Update(DT);
}
catch (Exception ex)
{
    textBox.Text = "エラーが発生しました。" + ex.Message;
}

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

トランザクション制御ありの更新
OleDbCommandBuilder CB = new OleDbCommandBuilder(DA);

DA.InsertCommand = CB.GetInsertCommand();
DA.UpdateCommand = CB.GetUpdateCommand();
DA.DeleteCommand = CB.GetDeleteCommand();

CONN.Open();

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

DA.InsertCommand.Transaction = TRN;
DA.UpdateCommand.Transaction = TRN;
DA.DeleteCommand.Transaction = TRN;

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

上の例で INSERT, UPDATE, DELETE について同じような記述が3行が並んでいる箇所があるが、実行される可能性がないものは書かなくてもよい。例えば、行削除が行なわれないことが
分かっているならDELETE部分の記述は不要である。

参考:DB 設計者のための明解 ADO.NET 第 1 回

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

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?