【解決方法】あるテーブルから別のテーブルに sqlite データを転送する


vb.net を使用して 1 つのテーブルを持つアプリを作成し、データを入力しました。
次に、別のテーブルが必要だと判断したので、元のテーブルを削除せずに別のテーブルを作成しました。両方のテーブルは同じ列名を持ちます。

ImportRowを使用して、あるテーブルから別のテーブルにデータを移動したいと考えています
ここで、列 tx Year はテキストボックス内の値、つまり 2021 と等しくなります。

この元のテーブルを DataGridView にロードできるので、テーブルは有効になります。

質問

ImportRow はデータを他のテーブルに移動する最良の方法ですか?
元のテーブルのデータのみがインポートされるように、txyear = 2021 という条件を設定するにはどうすればよいですか?
元のテーブルから txyear = 2021 を含むすべての行を削除しますか?

私が試したこと:

2 つのテーブルを作成するコードは次のとおりです。

VB
Public Sub makeTxData()

     'create table TxDataTable String for cmd
     Dim create_table As String = String.Empty
     create_table = "CREATE TABLE IF NOT EXISTS TxData(
                     TID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                     txSortDate TEXT,
                     txAmount TEXT,
                     txYear INTEGER,
                     txSearchMonth INTEGER)"

     Dim dbTable As String = "TxDataTable"

     If Not My.Computer.FileSystem.FileExists(dbTable) Then
         Try
             Using conn As New SQLiteConnection(connStr)
                 conn.Open()
                 Using cmd As New SQLiteCommand(create_table, conn)
                     cmd.ExecuteNonQuery()
                 End Using
             End Using
             tbMessage.Text = "DB Created Select BACK"
         Catch ex As Exception
             tbMessage.Text = "TxData Table FAILED"
         End Try
     End If

 End Sub

TxArchiveData の作成には同じコード構造が使用されました

VB
Dim dbTable As String = "TxArchiveData"

これがImportRowを使用しようとしているコードです

VB
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    Dim TxDataTable As New DataTable
    Dim TxArchiveData As New DataTable

    Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
        conn.Open()
        Using cmd As New SQLiteCommand("", conn)

            cmd.CommandText = "SELECT * FROM TxData"
            For Each dr As DataRow In TxDataTable.Rows
                TxArchiveData.ImportRow(dr)
            Next

        End Using
    End Using

End Sub

解決策 1

元のテーブルから関連するレコードを SELECT して、新しいテーブルにレコードを挿入する単純なアプリを作成する方が早いでしょう。 見る SQLiteの挿入[^]。

解決策 3

上記は完全な解決策ではありません、申し訳ありません…

「2021」のように「txyear」列が TextBox の値と等しい場合など、特定の条件に基づいてデータを移動するには、両方のテーブルで同じフィールド名を持つ「ImportRow」を使用するコードは次のようになります。テーブルからテーブル、またはデータベースからデータベースへの混乱についての上記のコメント) –

VB.NET
Imports System
Imports System.Data
Imports System.Data.SQLite

Module Program
    Sub Main()
        Dim connectionString As String = "Your SQLite connection string Hhere..."

        Using sourceConnection As New SQLiteConnection(connectionString)
            Using destinationConnection As New SQLiteConnection(connectionString)
                sourceConnection.Open()
                destinationConnection.Open()

                'Assume you have sourcetable and destinationtable already defined...
                Dim sourceTable As New DataTable("SourceTable")
                Dim destinationTable As New DataTable("DestinationTable")

                'Assume you have fetched data into your sourceTable...

                ' Assuming txtYear is a TextBox with the desired year value as per your question...
                Dim yearToFilter As String = txtYear.Text

                For Each sourceRow As DataRow In sourceTable.Rows
                    'Check if the 'txYear' column equals the specified year...
                    If sourceRow("txYear").ToString() = yearToFilter Then
                        'Use ImportRow to copy the structure and data of the row over...
                        Dim destinationRow As DataRow = destinationTable.NewRow()
                        destinationRow.ImportRow(sourceRow)

                        'Add the new row to your new destination table...
                        destinationTable.Rows.Add(destinationRow)
                    End If
                Next

                'Now you can work with the destinationTable, which contains the copied data based on the condition set in year, in this case 2021...
            End Using
        End Using
    End Sub
End Module

解決策 2

ImportRow はデータを他のテーブルに移動する最良の方法ですか?

私はまだ「ImportRow」の使い方がわかりません。@Richard MacCutchan によると、あるテーブルからデータを選択し、そのデータを別のテーブルに挿入する単純なアプリを考え始めました。 それでは、Insert 関数でデータを他のテーブルに追加するために、データをどこに保存すればよいでしょうか。
Google で少し検索して、私のアイデアに似たコードを見つけました。コピーして貼り付けて試してください。
Holly Cow これはうまくいきました。このことに気づき、コードを見つけたサイトに戻りました。
驚いたことに、それは AI コード生成サイトでした。DB に接続するプロセスが理解できるようにコードをリファクタリングしたとしても、これを認めたいのは何ですか
テーブル内の実際の列を参照するために「@Column1」を使用するとは思いもよりませんでした。
このコードには、データを挿入すると 2 回目の試行でデータが得られるという欠点が 1 つあります。
{“制約が失敗しました” & vbCrLf & “UNIQUE 制約が失敗しました: TxArchiveData.TID”}
これを修正する方法がわかりません。進歩することを願っています

どうか私を炎上させないでください。ここにその啓示へのリンクがあります
コードジェネレーター – CodePal[^]

これは私のリファクタリングされたコードと CodePal AI コードの一部です
データを 2 回アーカイブできないようにエラー トラップを追加しました

Private Sub DataPull()

    ' Represents a utility function for writing data from one table to another in the same database.
    '
    ' PARAMETERS:
    I()
    If count > 0 Then
        MessageBox.Show("That Year " + tbYear.Text + " Has Been Archived", "Warning", MessageBoxButtons.OK)
    End If
    Dim sourceTable As String = "TxData"
    Dim destinationTable As String = "TxArchiveData"

    ' EXCEPTION:
    ' Throws SqlException if there is an error executing the SQL query.

    Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
        conn.Open()
        ' Create a SQL command to select all data from the source table.
        Using cmd As New SQLiteCommand("", conn)
            cmd.CommandText = $"SELECT * FROM {sourceTable} WHERE txYear =" & tbYear.Text
            ' Execute the select command and retrieve the data.
            Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
                ' Create a SQL command to insert the data into the destination table.
                Using cmd2 As New SQLiteCommand("", conn)
                    cmd2.CommandText = $"INSERT INTO {destinationTable} VALUES (@Column1, @Column2, @Column3,@Column4,@Column5)"
                    ' Prepare the insert command parameters.
                    cmd2.Parameters.Add("@Column1", DbType.Int64)
                    cmd2.Parameters.Add("@Column2", DbType.String)
                    cmd2.Parameters.Add("@Column3", DbType.String)
                    cmd2.Parameters.Add("@Column4", DbType.Int64)
                    cmd2.Parameters.Add("@Column5", DbType.Int64)

                    ' Loop through the data and insert it into the destination table.
                    While rdr.Read()
                        ' Set the parameter values.
                        cmd2.Parameters("@Column1").Value = rdr.GetInt64(0)
                        cmd2.Parameters("@Column2").Value = rdr.GetString(1)
                        cmd2.Parameters("@Column3").Value = rdr.GetString(2)
                        cmd2.Parameters("@Column4").Value = rdr.GetInt64(3)
                        cmd2.Parameters("@Column5").Value = rdr.GetInt64(4)

                        ' Execute the insert command.
                        cmd2.ExecuteNonQuery()
                        count = count + 1
                        tbInfo.Text = count.ToString
                    End While
                End Using
            End Using
            End Using
    End Using
End Sub
Private Sub I()
    Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
        conn.Open()

        Using cmd As New SQLiteCommand("", conn)
            cmd.CommandText = "SELECT COUNT(*) FROM TxArchiveData WHERE txYear = " & tbYear.Text
            'Dim count As Integer Needs to be declard as toplevel variable
            'OR in a DataModule as gv_count it is used in DataPull() Sub
            cmd.Parameters.AddWithValue("@value", tbYear)
            count = CInt(cmd.ExecuteScalar())
        End Using
    End Using

End Sub

コメント

タイトルとURLをコピーしました