0

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

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

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)

任何帮助将不胜感激

4

2 回答 2

1

A 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
于 2012-09-19T14:23:07.653 回答
0

自从我编写任何 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()
于 2012-09-19T14:33:42.930 回答