C# でのトランザクション処理の実装方法

トランザクション処理を実装するには、まずデータベース接続を確立し、BeginTransaction() メソッドを使用してトランザクションを開始します。続いて、SqlCommand オブジェクトの Transaction プロパティに取得したトランザクションを割り当てます。コマンドを実行後、Commit() メソッドでトランザクションを確定、または Rollback() を使って取り消すことができます。

トランザクション実行の基本手順

  1. データベース接続を確立します。
  2. BeginTransaction() を呼び出し、トランザクションを開始します。
  3. 作成したトランザクションを、使用する SqlCommand オブジェクトに割り当てます。
  4. SQL コマンドを実行します。
  5. 処理が成功した場合は Commit() を呼び出し、失敗した場合は Rollback() を実行します。

サンプルコード:単一のSQL操作におけるトランザクション処理


// 接続文字列の準備
string connectionString = "data source=.;initial catalog=Myschool;uid=sa;pwd=123";
// 接続オブジェクトの作成
SqlConnection connection = new SqlConnection(connectionString);
// SQL文の定義
string query = "INSERT INTO grade (name) VALUES (@gradename)";
// パラメータの設定
SqlParameter parameter = new SqlParameter("@gradename", txtGradeName.Text);
// コマンドオブジェクトの作成
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.Add(parameter);

try
{
    connection.Open();
    SqlTransaction transaction = connection.BeginTransaction();
    command.Transaction = transaction;

    int result = command.ExecuteNonQuery();

    if (result > 0)
    {
        transaction.Commit();
        MessageBox.Show("登録成功");
    }
    else
    {
        transaction.Rollback();
        MessageBox.Show("登録失敗");
    }
}
catch (Exception ex)
{
    MessageBox.Show("エラーが発生しました: " + ex.Message);
}
finally
{
    if (connection.State == System.Data.ConnectionState.Open)
    {
        connection.Close();
    }
}
    

複数のSQL操作をトランザクションで処理する方法

複数のテーブルに対して一括でトランザクション処理を行う際は、すべての操作が成功した場合のみコミットを行い、いずれかの処理が失敗した場合はすべてをロールバックします。

サンプルコード:複数SQL操作に対するトランザクション処理


public static void ExecuteMultipleQueries(List<string> queries)
{
    using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString))
    {
        conn.Open();
        SqlTransaction transaction = conn.BeginTransaction();
        SqlCommand command = conn.CreateCommand();
        command.Transaction = transaction;

        try
        {
            foreach (string query in queries)
            {
                if (!string.IsNullOrWhiteSpace(query))
                {
                    command.CommandText = query;
                    command.ExecuteNonQuery();
                }
            }
            transaction.Commit();
        }
        catch (Exception ex)
        {
            transaction.Rollback();
            throw new Exception("トランザクション処理中にエラーが発生しました。", ex);
        }
    }
}

private void ExecuteButton_Click(object sender, EventArgs e)
{
    try
    {
        List<string> queryList = new List<string>();
        queryList.Add("INSERT INTO [user] (name, age) VALUES ('たろう', '5')");
        queryList.Add("UPDATE [class] SET [name] = '保育園' WHERE id = 1");

        ExecuteMultipleQueries(queryList);
        MessageBox.Show("操作成功");
    }
    catch (Exception ex)
    {
        MessageBox.Show("操作失敗: " + ex.Message);
    }
}
    

タグ: C# SQL Server トランザクション データベース処理 データ整合性

8月12日 15:46 投稿