首页 > 开发 > 综合 > 正文

HOW TO: update a Database from a DataSet Object Us

2024-07-21 02:22:34
字体:
来源:转载
供稿:网友

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  
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表