从datatable更新sqlite文件

时间:2016-05-11 20:09:25

标签: vb.net sqlite datatable sql-update

旨在将db3(sqlite)文件中的表加载到数据表中。然后将此数据表加载到datagridview中以允许对其进行编辑。然后我想将已编辑的数据表保存回原始的db3文件 - 覆盖任何更改。

我已经将db3 +中的表格转换为DGV。我不会在数据表中包含任何代码到dgv。只需要如何将此数据写回db3文件。我该怎么做呢?代码:

Imports System.Data.SQLite

Public Class DBOps
Public Function ImportGEDb3(Filepath As String) As DataTable
    Dim dt As New DataTable("Data")
    Dim cnn As New SQLiteConnection("Data Source='" & Filepath & "'")
    cnn.Open()
    Dim mycommand As New SQLiteCommand(cnn)
    mycommand.CommandText = "Select * from Data"
    Dim reader As SQLiteDataReader = mycommand.ExecuteReader()
    dt.Load(reader)
    reader.Close()
    cnn.Close()
    Return dt
End Function

Public Sub SaveGEDb3(dt as datatable, filepath as string)
 ' save passed datatable to File above
end sub 
end class

1 个答案:

答案 0 :(得分:1)

SQLiteDataAdapter类是此类更新的最简单选择。类的Update方法扫描传递的DataTable,并且对于具有与DataRowState不同的RowState属性的每一行,Unchanged执行相应的INSERT,DELETE,UPDATE命令(如果SELECT命令从DataTable中提取主键)。因此,假设您的SELECT * FROM Data也返回表的主键,您可以更改代码以利用SQLiteDataAdapter功能

Imports System.Data.SQLite

Public Class DBOps
    ' Global because you create it in the ImportGEDb3 and use it in the SaveGEDB3 '
    Private daImport As SQLiteDataAdapter

    Public Function ImportGEDb3(Filepath As String) As DataTable
        Dim dt As New DataTable("Data")
        daImport = new SQLiteDataAdapter("Select * from Data", "Data Source='" & Filepath & "'")                
        daImport.Fill(dt)

        ' This is critical, it is the SQLiteCommandBuilder that takes '
        ' the SQLiteDataAdapter SELECT statement and builds the required'
        ' INSERT,UPDATE,DELETE commands.'
        Dim builder = new SQLiteCommandBuilder(daImport)
        Return dt
    End Function

    Public Sub SaveGEDb3(dt as datatable)
      if daImport IsNot Nothing Then
         daImport.Update(dt)
      End If
    End Sub 
End class