データを更新・削除するロジックサンプル
前回記事はSELECT文を発行してデータを取得するロジックでしたが、今度はINSERT文のサンプルロジックです。
前回の記事
なお、このブログ内に記載しているソースの転載・転用については何も縛りはありません。
ご使用の状況の如何に問わず、作者たる当方は結果についてその責任を一切負いません。ご使用は自己責任の範囲でお願いいたします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | Private Function SQLite_Insert( ByVal GetData As DataTable, ByVal strSQLiteDB As String ) As Boolean SQLite_Insert = False Try 'データベースファイルの存在確認 If System.IO.File.Exists(strSQLiteDB) = False Then '存在しない場合はエラーを出力して終了する MessageBox.Show( "エラー" , "エラーが発生しました。" , MessageBoxButtons.OK, MessageBoxIcon. Error ) Return False Exit Function End If Dim Connection As New SQLiteConnection Dim Command As SQLiteCommand Dim DataExecute As Integer Dim strSQL As String = String .Empty '接続文字列を設定 Connection.ConnectionString = "Version=3;Data Source=" & strSQLiteDB & ";New=False;Compress=True;" 'オープン Connection.Open() 'コマンド作成 Command = Connection.CreateCommand For intI = 0 To GetData.Rows.Count - 1 'データテーブルの内容をSQLでDBに書き込む '<<< SQLで挿入【NM01TOKU】 >>> strSQL = "INSERT INTO 得意先マスタ VALUES " strSQL += "(" & CType (GetData.Rows(intI).Item( "得意先コード" ).ToString, Long ) strSQL += ",'" & GetData.Rows(intI).Item( "得意先名称1" ).ToString.Replace( "'" , "" ) & "'" strSQL += ",'" & GetData.Rows(intI).Item( "得意先名称2" ).ToString.Replace( "'" , "" ) & "'" strSQL += ",'" & GetData.Rows(intI).Item( "大分類コード" ).ToString & "'" strSQL += ",'" & GetData.Rows(intI).Item( "中分類コード" ).ToString & "'" strSQL += ",'" & GetData.Rows(intI).Item( "小分類コード" ).ToString & "')" 'SQLをセット Command.CommandText = strSQL 'データ更新 DataExecute = Command.ExecuteNonQuery() Next '破棄 Command.Dispose() Connection.Close() Connection.Dispose() Return True Catch ex As Exception 'ここでエラー処理 Return False End Try End Function |
このサンプルではDataTableで格納されているデータをSQLite上の得意先マスタに格納しているサンプルです。
INSERT時に.Replace(“‘”, “”)しているのは得意先名称1・2に「’」が登録になっていることの対応処理です。
まだまだ応用や使い道について調べてメモします。次回へ続きます。