【问题标题】:Saving record with dataset使用数据集保存记录
【发布时间】:2012-09-11 20:50:29
【问题描述】:

我想使用数据集在数据库中保存一条记录,但我的数据没有提交到我的数据库中。

我的代码可以在下面查看:

Dim mydataset1 As New MyDataSet

Dim row As DataRow = mydataset1.Tables("testtable").NewRow()

With row
    .Item("name") = "Segun Omotayo"
    .Item("address") = "Abuja"
End With

mydataset1.Tables("testtable").Rows.Add(row)

任何帮助将不胜感激

【问题讨论】:

  • 表“testtable”在哪里被添加到数据集中,通过什么方式?在典型设置中,这应该由适配器使用数据库中的数据填充数据表来完成

标签: vb.net winforms dataset


【解决方案1】:

DataSet/DataTable 是数据库的离线/内存表示。如果要更新数据库,需要使用DataAdapter。

例如(假设您使用的是 MS-Sql-Server):

Public Function UpdateDataSet(dataSet As DataSet) As Int32
    Using con = New SqlConnection(My.Settings.SqlConnection)
        Dim sql = "INSERT INTO TUser(Name,Address)VALUES(@Name,@Address)"
        Using cmd = New SqlCommand(sql, con)
            cmd.Parameters.Add(New SqlParameter("@Name", SqlDbType.VarChar))
            cmd.Parameters.Add(New SqlParameter("@Address", SqlDbType.VarChar))
            Using da = New SqlDataAdapter()
                da.InsertCommand = cmd
                con.Open()
                Dim rowCount = da.Update(dataSet)
                Return rowCount
            End Using
        End Using
    End Using
End Function

【讨论】:

    【解决方案2】:

    自从我编写任何 VB.NET 或使用数据适配器/数据集/数据表以来,我可能在这里生疏了很长时间,但我认为如果您决定采用这条路线,您将需要这样的代码:

    Dim connection As New SqlConnection("#####YourConnectionString#####")
    connection.Open()
    
    Dim adapter As New SqlDataAdapter("SELECT * FROM testtable", connection)
    
    ' For the line below to work, you must have a primary key field in "testtable"
    Dim builder As New SqlCommandBuilder(adapter)
    
    Dim testtable As New DataTable("testtable")
    
    adapter.Fill(testtable)
    
    Dim row As DataRow = testtable.NewRow()
    
    With row
        .Item("name") = "Segun Omotayo"
        .Item("address") = "Abuja"
    End With
    
    testtable.Rows.Add(row)
    
    adapter.Update(testtable)
    
    connection.Close()
    

    【讨论】:

      猜你喜欢
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多