INSERT
データセットへのデータ操作(行挿入)後、DBへのデータ反映(データアダプタのUpdateメソッドによるINSERT文の実行)を行うサンプルコードです。
using System; using System.Data; using System.Data.Common; namespace SqliteExample { public class ArtificialNewType2Insert { public static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("コマンドライン引数エラー"); Console.WriteLine("Usage: ainsert2.exe [id] [name]"); return; } string dpstr = "Mono.Data.Sqlite"; string constr = "Data Source=/home/sta/data/TestData.db"; string sstr = "SELECT ProductID, ProductName, " + "Price, ProductDescription " + "FROM Products"; // INSERT用SQL文字列 string istr = "INSERT INTO Products " + "(ProductID, ProductName) " + "VALUES (@P1, @P2)"; DbProviderFactory dpf = DbProviderFactories.GetFactory(dpstr); // 1.DBコネクションオブジェクト作成 using (DbConnection dbcon = dpf.CreateConnection()) { dbcon.ConnectionString = constr; dbcon.Open(); try { // トランザクション開始 using (DbTransaction tran = dbcon.BeginTransaction()) // 2.データアダプタオブジェクト作成 using (DbDataAdapter da = dpf.CreateDataAdapter()) // SELECT用コマンドオブジェクト作成 using (DbCommand scmd = dbcon.CreateCommand()) // INSERT用コマンドオブジェクト作成 using (DbCommand icmd = dbcon.CreateCommand()) // 3.データセットオブジェクト作成 using (DataSet ds = new DataSet()) { // SELECT用コマンドオブジェクト設定 scmd.CommandText = sstr; da.SelectCommand = scmd; // 4.データセットへのデータ格納 da.Fill(ds, "Products"); DataTable dt = ds.Tables["Products"]; // 5.データセットへのデータ操作 DataRow nrow = dt.NewRow(); // パターン1 //nrow["ProductID"] = 4; //nrow["ProductName"] = "drill"; // パターン2 nrow[0] = args[0]; nrow[1] = args[1]; // 行挿入 dt.Rows.Add(nrow); // INSERT用コマンドオブジェクト設定 icmd.CommandText = istr; // パラメータ設定 // @P1 DbParameter p1 = icmd.CreateParameter(); p1.ParameterName = "@P1"; p1.SourceColumn = "ProductID"; icmd.Parameters.Add(p1); // @P2 DbParameter p2 = icmd.CreateParameter(); p2.ParameterName = "@P2"; p2.SourceColumn = "ProductName"; icmd.Parameters.Add(p2); // トランザクションセット icmd.Transaction = tran; da.InsertCommand = icmd; try { // 6.データセットからDBへのデータ反映 da.Update(ds, "Products"); // コミット tran.Commit(); } catch(Exception ex) { // ロールバック tran.Rollback(); Console.WriteLine("更新エラー: {0}", ex.Message); } } } finally { if (dbcon != null) { dbcon.Close(); } } } } } } /* * ビルド: * * gmcs ainsert2.cs -r:System.Data.dll * * 実行: * * mono ainsert2.exe [id] [name] * */
データセットへのデータ操作
インデクサに、インデックス番号を指定してDataRowオブジェクトの各列に対応する値を設定するパターンとカラム名を指定して値を設定するパターンを試してみました。
トランザクション
データ更新を伴うことから、トランザクション処理を付加しています。データアダプタを使用する場合、メソッド実行時にDBコネクションのオープン・クローズを自動的に行うので明示的にオープンを行う必要はありませんが、トランザクション処理の付加に伴い、明示的にオープンを行っています。
