我想使用数据集在数据库中保存记录,但我的数据没有提交到我的数据库中。
我的代码可以在下面查看:
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)
任何帮助将不胜感激
答案 0 :(得分: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
答案 1 :(得分: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()