データベースの情報を更新(Delete/Insert/Update)する
基本
- 事前に conn.Open() してある前提です
- 下記では処理の流れが分かり易い様にTransactionを使用していません
- 下記では処理の流れが分かり易い様に例外処理を省いています
DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "update sampletable set name = 'テスト' where id = 1"; int resultCount = cmd.ExecuteNonQuery(); cmd?.Dispose(); conn.Close(); return resultCount;
Transactionを使用して更新する
- 一般的にDB更新はTransactionを使って行う
- Transactionを使うと、SQLエラー発生時に未コミットのSQL結果をすべてRollBack(キャンセル)してデータベースに不整合が生じるのを避けることができる
DbTransaction transaction = null; DbCommand cmd = null; try { transaction = conn.BeginTransaction(); cmd = conn.CreateCommand(); cmd.CommandText = "update sampletable set name = 'テスト' where id = 1"; int resultCount = cmd.ExecuteNonQuery(); transaction.Commit(); return resultCount; } catch { transaction?.RollBack(); throw; } finally { cmd?.Dispose(); transaction?.Dispose(); conn?.Close(); }