开发者

Updating Database from DataSet

I am having trouble updating my Database from my code using a DataSet. I'm using SQL Server 2008 and Visual Studio 2008. Here is what I've done so far.

I have created a table in SQL Server called MyTable which has two columns: id nchar(10), and name nchar(50).

I have then created a datasource in m开发者_如何学Cy VB.net project that consists of this table using the dataset wizard and called this dataset MyDataSet.

I run the following code on a button click:

    Try
        Dim myDataSet As New MyDataSet
        Dim newRow As MyDataSet.MyTableRow = myDataSet.MyTable.NewMyTableRow
        newRow.BeginEdit()
        newRow.id = "1"
        newRow.name = "Alpha"
        newRow.EndEdit()
        myDataSet.MyTable.AddMyTableRow(newRow)
        myDataSet.AcceptChanges()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

when I run this and check the rows in SQL Server it returns 0 rows

What have I missed? How can I add these rows / save changes in a dataset to the database? I have seen other examples that use a TableAdapter but I don't think I want to do this, I think I should be able to achieve this just using a DataSet. Am I mistaken?

Help is greatly appreciated!


You must call the Update method on your DataAdapter()

MyDataAdapter.Update(MyDataSet)

Of course you will have to make a DataAdapter or TableAdapter with a the necessary commands to write the changes to the database.

A DataSet is an in memory / disconnected "database".

A DataAdapter is the widget that communicates with the DataBase. There are different DataAdapters for different Databases, for SQL Server, use SqlDataAdapter.

Calling AcceptChanges will mark all your changes as already changed, so when you update your database with your dataadapter, the changes will not be written to the database.

If you want to persist the data to the database (the ADO.NET way), you will have to use a DataAdapter or TableAdapter.


Don't call AcceptChanges, that just resets all of the change tracking information on the DataTable to indicate that the rows are current.

The DataSet itself doesn't do any database interaction. You need to use the proper DataAdapter (in this case the TableAdapter that you said you didn't want to use) and save the table by calling Update.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜