📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)
| 227行目: | 227行目: | ||
== UPDATE / INSERT / DELETE == | == UPDATE / INSERT / DELETE == | ||
ロールバック処理自体も失敗する可能性があるため、2重のtry-catch構造を使用することにより、ロールバック処理中のエラーも適切に処理できる。<br> | |||
<br> | |||
<syntaxhighlight lang="c++"> | <syntaxhighlight lang="c++"> | ||
// 接続文字列の生成 | |||
CString strCon = _T("DSN=MS Access 97 Database;UID=Admin;PWD="); | |||
CDatabase db; | |||
bool bTransStarted = false; // トランザクションの状態を追跡するフラグ | |||
try { | |||
// 接続 | // 接続 | ||
db.OpenEx | if (!db.OpenEx(strCon, CDatabase::noOdbcDialog)) { | ||
// db. | AfxMessageBox(_T("データベース接続に失敗しました")); | ||
// | return -1; | ||
// | } | ||
// | |||
// トランザクション開始 | |||
db.BeginTrans(); | |||
bTransStarted = true; | |||
// SQLコマンドの実行 | |||
db.ExecuteSQL(_T("create table test(a text, b text)")); | |||
// db.ExecuteSQL(_T("insert into test(a,b) values('inaba','minoru')")); | |||
// db.ExecuteSQL(_T("delete from test where a='inaba'")); | |||
// db.ExecuteSQL(_T("DROP TABLE test")); | |||
// | // トランザクションのコミット | ||
db. | db.CommitTrans(); | ||
bTransStarted = false; | |||
} | |||
catch (CDBException *e) { | |||
// データベース固有のエラー処理 | |||
if (bTransStarted) { | |||
try { | |||
db.Rollback(); | |||
} | |||
catch (...) { | |||
AfxMessageBox(_T("ロールバック中にエラーが発生しました")); | |||
} | |||
} | } | ||
catch(...) | |||
CString strError; | |||
strError.Format(_T("データベースエラー: %s"), e->m_strError); | |||
AfxMessageBox(strError); | |||
e->Delete(); | |||
} | |||
catch (...) { | |||
// その他の予期せぬエラー処理 | |||
if (bTransStarted) { | |||
try { | |||
db.Rollback(); | |||
} | |||
catch (...) { | |||
AfxMessageBox(_T("ロールバック中にエラーが発生しました")); | |||
} | |||
} | } | ||
AfxMessageBox(_T("予期せぬエラーが発生しました")); | |||
} | } | ||
// データベースを閉じる | |||
if (db.IsOpen()) db.Close(); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<br><br> | <br><br> | ||