// updateds.cs using System; using System.Data; using System.Data.SqlClient; public class UpdateFromDataSet { public static void Main() { string connStr = "Server=(local)\\NetSDK;" + "Trusted_Connection=yes;" + "database=pubs"; string selectStr = "SELECT pub_id, pub_name FROM publishers"; // 接続用オブジェクトの作成 SqlConnection conn = new SqlConnection(); conn.ConnectionString = connStr; // select用コマンド・オブジェクトの作成 SqlCommand selectCmd = new SqlCommand(); selectCmd.Connection = conn; selectCmd.CommandText = selectStr; // データアダプタの作成 SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = selectCmd; // データセットへの読み込み DataSet ds = new DataSet(); da.Fill(ds, "publishers"); DataTable dt = ds.Tables["publishers"]; // 主キーの設定 dt.PrimaryKey = new DataColumn[] { dt.Columns["pub_id"] }; // データの更新 DataRow targetRow; targetRow = dt.Rows.Find("0736"); targetRow["pub_name"] = "新月書店"; targetRow = dt.Rows.Find("1756"); targetRow["pub_name"] = "ラモーナ出版"; // update用コマンド・オブジェクトの作成 string updateStr = "UPDATE publishers" + " SET pub_name = @PubName WHERE pub_id = @PubID"; SqlCommand updateCmd = new SqlCommand(); updateCmd.Connection = conn; updateCmd.CommandText = updateStr; SqlParameter p1 = new SqlParameter(); p1.ParameterName = "@PubId"; p1.SourceColumn = "pub_id"; updateCmd.Parameters.Add(p1); SqlParameter p2 = new SqlParameter(); p2.ParameterName = "@PubName"; p2.SourceColumn = "pub_name"; updateCmd.Parameters.Add(p2); da.UpdateCommand = updateCmd; // データベースの更新 da.Update(ds, "publishers"); } } // コンパイル方法:csc updateds.cs