0
0

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

Last updated at Posted at 2015-06-18

複数のDataTableの変更を同時にDBに反映する際のトランザクション制御

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);

String sql2 = "SELECT 部署名, 住所 FROM 部署;
OleDbDataAdapter DA2 = new OleDbDataAdapter(sql2, CONN);
DataTable DT2 = new DataTable();
DT2.TableName = "部署DT";
DA2.Fill(DT2);

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

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

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

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

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

OleDbCommandBuilder CB2 = new OleDbCommandBuilder(DA2);

DA2.InsertCommand = CB2.GetInsertCommand();
DA2.UpdateCommand = CB2.GetUpdateCommand();
DA2.DeleteCommand = CB2.GetDeleteCommand();

CONN.Open();

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

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

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

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

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

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?