HOW TO: Update a Database from a DataSet Object Using Visual Basic .NET-.Net技术-3P代码网
繁体中文
设为首页
加入收藏
当前位置:.Net技术首页 >> Asp.Net开发 >> HOW TO: Update a Database from a DataSet Object Using Visual Basic .NET

HOW TO: Update a Database from a DataSet Object Using Visual Basic .NET

2007-08-15 08:00:00  作者:  来源:互联网  浏览次数:0  文字大小:【】【】【
简介:HOW TO: Update a Database from a DataSet Object Using Visual Basic .NET This article discusses a Beta release of a Microsoft product. The information in this article is provided as-is and is subje...

HOW TO: Update a Database from a DataSet Object Using Visual Basic .NET

This article discusses a Beta release of a Microsoft product. The information in this article is provided as-is and is subject to change without notice.

No formal product support is available from Microsoft for this Beta product. For information about obtaining support for a Beta release, please see the documentation included with the Beta product files, or check the Web location from which you downloaded the release.

--------------------------------------------------------------------------------

The information in this article applies to:

Microsoft Visual Basic .NET Beta 2

--------------------------------------------------------------------------------

IN THIS TASK

SUMMARY

Requirements

How to Update a Database from a DataSet Object

Complete Code Listing

REFERENCES

SUMMARY

DataSet objects, a key part of data access in the Microsoft .NET Framework, are in-memory objects that can hold tables, views, and relationships. This article demonstrates how to take a DataSet that contains data (which is loaded from a database), modify that data, and then send it back to the database to update the original source.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:

Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows NT 4.0 Server

Microsoft SQL Server version 7.0 or 2000, or Microsoft Data Engine (MSDE), with the PUBS sample database installed

Microsoft Visual Studio .NET

This article assumes that you are familiar with the following topics:

Database terminology

Structured Query Language (SQL)

back to the top

How to Update a Database from a DataSet Object

This section demonstrates how to use the DataSet object to update data in a database. It is important to remember that you can also use a SqlCommand object to insert, update, and delete data in a database directly.

Understanding the concepts in the following Microsoft Knowledge Base article will help you understand this article:

Q301216 HOW TO: Populate a DataSet Object from a Database

Some of the topics that are covered in Q301216 include how to retrieve data from a database and into a DataSet , and how the DataSet is separate and distinct from the database.

After the DataSet is loaded, you can modify the data, and the DataSet will track the changes. The DataSet object can be considered an in-memory cache of data that is retrieved from a database and consists of a collection of tables, relationships, and constraints.

To update a DataSet and send those updates back to the database, follow these steps:

Open Visual Studio .NET

Create a new Console Application in Visual Basic .NET. By default, Visual Studio creates a Static Module and an empty Main() procedure.

Make sure that the project contains a reference to the System and System.Data namespaces. Use the Imports on the System , SystemData , and System.Data.SqlClient namespaces so that you are not required to qualify declarations from these namespaces later in your code. You must use these statements prior to any other declarations.

Imports System

Imports System.Data

Imports System.Data.SqlClient

Before you can modify the data and submit the changes back to the database, you must load the information into the DataSet . For the detailed procedure, refer to Q301216 . To avoid duplication, the code in this step is not presented in detail.

The connection string in the following code points to a SQL Server that is located on the local computer (or the computer where the code is running) that has a blank password for the 'sa' account. Replace this string with your own settings, if required. In brief, a connection is created, and then a data adapter is created, which is used to fill the DataSet with data.

Dim sConnectionString As String

' Modify the following code to correctly connect to your SQL Server.

sConnectionString = "Password=;User ID=sa;" & _

"Initial Catalog=pubs;" & _

"Data Source=(local)"

Dim objConn As New SqlConnection(sConnectionString)

objConn.Open()

' Create an instance of a DataAdapter.

Dim daAuthors As _

New SqlDataAdapter("Select * From Authors", objConn)

' Create an instance of a DataSet and retreive data from the Authors table.

Dim dsPubs As New DataSet("Pubs")

daAuthors.FillSchema(dsPubs, SchemaType.Source, "Authors")

daAuthors.Fill(dsPubs, "Authors")

Now that the data is loaded, you can modify it. There are many ways to add a row (or record). This code sample uses a three step procedure:

Obtain a new DataRow object from the DataTable .

Set the DataRow field values as necessary.

Pass that new object into the Add method of the DataTable.Rows collection.

Paste the following code after the code in step 4:

'*****************

'BEGIN ADD CODE

' Create a new instance of a DataTable

Dim tblAuthors As DataTable

tblAuthors = dsPubs.Tables("Authors")

Dim drCurrent As DataRow

' Obtain a new DataRow object from the DataTable.

drCurrent = tblAuthors.NewRow()

' Set the DataRow field values as necessary.

drCurrent("au_id") = "993-21-3427"

drCurrent("au_fname") = "George"

drCurrent("au_lname") = "Johnson"

drCurrent("phone") = "800 226-0752"

drCurrent("address") = "1956 Arlington Pl."

drCurrent("city") = "Winnipeg"

drCurrent("state") = "MB"

drCurrent("contract") = 1

'Pass that new object into the Add method of the DataTable.Rows collection.

tblAuthors.Rows.Add(drCurrent)

MsgBox("Add was successful.")

'END ADD CODE

To edit existing rows, obtain the appropriate DataRow object, and provide new values for one or more columns. You must first find the correct row, a process that is made much easier because you loaded the schema of the table as well as the data (the call to FillSchema in step 4). With the schema in place, the table knows which column is its primary key, and the Find method of the Rows collection is available.

The Find method returns the DataRow object with a specific value in its primary key (in this case, au_id). After you have that DataRow, you can modify the columns. You do not have to wrap the modifications in BeginEdit and EndEdit , but this simplifies the work that the DataSet has to do and allows the DataSet to perform its validation checks all at once upon the EndEdit call. Paste the following code after the ADD code:

'*****************

'BEGIN EDIT CODE

drCurrent = tblAuthors.Rows.Find("213-46-8915")

drCurrent.BeginEdit()

drCurrent("phone") = "342" & drCurrent("phone").ToString.Substring(3)

drCurrent.EndEdit()

MsgBox("Record edited successfully")

'END EDIT CODE

To update the original database with all of these changes, pass the DataSet into the Update method of the DataAdapter object.

However, before you can call Update , you must set the InsertCommand , UpdateCommand , and DeleteCommand properties of the DataAdapter object. You can manually write SQL and populate these three properties with corresponding SqlCommand objects, but you can also use Visual Studio .NET to generate these three commands automatically.

To generate the required commands when they are needed, you must create an instance of the SqlCommandBuilder object and use the DataAdapter in the constructor. If you want to use this method, which is illustrated in the code sample to follow, you must have primary key information available for your table. To access primary key information, call FillSchema and set the MissingSchemaAction property of your DataAdapter to AddWithKey , or manually set the primary key in your code. Paste the following code after the EDIT code:

'*****************

'BEGIN SEND CHANGES TO SQL SERVER

Dim objCommandBuilder As New SqlCommandBuilder(daAuthors)

daAuthors.Update(dsPubs, "Authors")

MsgBox("SQL Server updated successfully" & chr(13) & "Check Server explorer to see changes")

' END SEND CHANGES TO SQL SERVER

To delete a row completely, use the Delete method of the DataRow object. Note that the Rows collection contains two methods, Remove and RemoveAt , which seem to delete the row but instead just remove the row from the collection. Only the Delete method sends your deletion back to the source database. Paste the following code after the SEND CHANGES TO SQL SERVER code:

'*****************

'BEGIN DELETE CODE

drCurrent = tblAuthors.Rows.Find("993-21-3427")

drCurrent.Delete()

MsgBox("Record deleted successfully")

'END DELETE CODE

Send the changes to SQL Server to remove the record that you added earlier. Paste the following code after the DELETE code:

'*****************

' CLEAN UP SQL SERVER

daAuthors.Update(dsPubs, "Authors")

MsgBox("SQL Server updated successfully" & Chr(13) & Chr(13) & "Check Server Explorer to see changes")

Save your project.

On the Debug menu, click Start to run the project. Notice that several message boxes appear, which indicate the progress of the code and allow you to review the current state of the data as the code progresses.

back to the top

Complete Code Listing

Imports System

Imports System.Data

Imports System.Data.SqlClient

Module Module1

Sub Main()

Dim sConnectionString As String

' Modify the following code to correctly connect to your SQL Server.

sConnectionString = "Password=;User ID=sa;" & _

"Initial Catalog=pubs;" & _

"Data Source=(local)"

Dim objConn As New SqlConnection(sConnectionString)

objConn.Open()

' Create an instance of a DataAdapter.

Dim daAuthors As _

New SqlDataAdapter("Select * From Authors", objConn)

' Create an instance of a DataSet and retreive data from the Authors table.

Dim dsPubs As New DataSet("Pubs")

daAuthors.FillSchema(dsPubs, SchemaType.Source, "Authors")

daAuthors.Fill(dsPubs, "Authors")

'*****************

'BEGIN ADD CODE

' Create a new instance of a DataTable

Dim tblAuthors As DataTable

tblAuthors = dsPubs.Tables("Authors")

Dim drCurrent As DataRow

' Obtain a new DataRow object from the DataTable.

drCurrent = tblAuthors.NewRow()

' Set the DataRow field values as necessary.

drCurrent("au_id") = "993-21-3427"

drCurrent("au_fname") = "George"

drCurrent("au_lname") = "Johnson"

drCurrent("phone") = "800 226-0752"

drCurrent("address") = "1956 Arlington Pl."

drCurrent("city") = "Winnipeg"

drCurrent("state") = "MB"

drCurrent("contract") = 1

'Pass that new object into the Add method of the DataTable.Rows collection.

tblAuthors.Rows.Add(drCurrent)

MsgBox("Add was successful.")

'END ADD CODE

'*****************

'BEGIN EDIT CODE

drCurrent = tblAuthors.Rows.Find("213-46-8915")

drCurrent.BeginEdit()

drCurrent("phone") = "342" & drCurrent("phone").ToString.Substring(3)

drCurrent.EndEdit()

MsgBox("Record edited successfully")

'END EDIT CODE

'*****************

'BEGIN SEND CHANGES TO SQL SERVER

Dim objCommandBuilder As New SqlCommandBuilder(daAuthors)

daAuthors.Update(dsPubs, "Authors")

MsgBox("SQL Server updated successfully" & chr(13) & "Check Server explorer to see changes")

' END SEND CHANGES TO SQL SERVER

'*****************

'BEGIN DELETE CODE

drCurrent = tblAuthors.Rows.Find("993-21-3427")

drCurrent.Delete()

MsgBox("Record deleted successfully")

'END DELETE CODE

'*****************

' CLEAN UP SQL SERVER

daAuthors.Update(dsPubs, "Authors")

MsgBox("SQL Server updated successfully" & Chr(13) & Chr(13) & "Check Server Explorer to see changes")

End Sub

End Module

back to the top

REFERENCES

For more information about using ActiveX Data Objects (ADO) .NET, DataSet objects, and SQL, refer the following Microsoft Web sites:

"Diving into Data Access" (an MSDN Voices column)

http://msdn.microsoft.com/voices/data.ASP

"ADO.NET for the ADO Programmer"

http://msdn.microsoft.com/library/techart/adonetdev.htm

MSDN Online .NET Developer Center

http://msdn.microsoft.com/net

back to the top

责任编辑:admin
相关文章