りおんクロニクル


C#でSQL Serverのレコードを更新する方法

Home【2026年版】C# / .NET入門と実践ガイド|基礎・業務アプリ開発・SQLite連携まで体系的に解説

C#でSQL Serverのレコードを更新する方法

サンプルコード


using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        // SQL Server接続文字列
        string connectionString = "Server=your_server_name;Database=your_database_name;User Id=your_username;Password=your_password;";

        // 更新するバンド変数(複数の値を保持)
        var parameters = new
        {
            ID = 1, // 更新する行のID
            NewValue1 = "新しい値1",
            NewValue2 = "新しい値2"
        };

        // 更新クエリ
        string query = "UPDATE YourTableName SET Column1 = @NewValue1, Column2 = @NewValue2 WHERE ID = @ID";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            try
            {
                connection.Open(); // 接続を開く
                
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    // バンド変数を使用してパラメータを追加
                    command.Parameters.AddWithValue("@ID", parameters.ID);
                    command.Parameters.AddWithValue("@NewValue1", parameters.NewValue1);
                    command.Parameters.AddWithValue("@NewValue2", parameters.NewValue2);

                    // クエリ実行
                    int rowsAffected = command.ExecuteNonQuery();
                    Console.WriteLine($"{rowsAffected} 行が更新されました。");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"エラーが発生しました: {ex.Message}");
            }
        }
    }
}
    

追加説明

前のページ  次のページ