HOW TO: Update a Database from a DataSet Object Us

<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 728x15, 创建于 08-4-23MSDN */ google_ad_slot = "3624277373"; google_ad_width = 728; google_ad_height = 15; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 160x600, 创建于 08-4-23MSDN */ google_ad_slot = "4367022601"; google_ad_width = 160; google_ad_height = 600; //--> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
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  

11AIQ9240525X.jpg
seover="window.statUs='正文--HOW TO: Update a Database from a DataSet Object Using Visual Basic .NET';return true">
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 728x15, 创建于 08-4-23MSDN */ google_ad_slot = "3624277373"; google_ad_width = 728; google_ad_height = 15; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 160x600, 创建于 08-4-23MSDN */ google_ad_slot = "4367022601"; google_ad_width = 160; google_ad_height = 600; //--> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
阅读更多
个人分类: .net
想对作者说点什么? 我来说一句

Java parse HTML to XHTML

2015年06月14日 33.84MB 下载

Database Explorer

2011年12月29日 69KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭