Anda di halaman 1dari 7

"0 !

How to populate a DataSet object from a database by using


Visual Basic .NET
This article was previously published under Q301216

This article has been archived. It is offered "as is" and will no longer be updated.

For a Microsoft Visual C# .NET version of this article, see 314145.

For a Microsoft Visual Basic 6.0 version of this article, see 168336.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
System
System.Data
System.Data.SqlClient

IN THIS TASK
SUMMARY
Requirements
Filling a DataSet
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 shows how to fill a DataSet object with the
results of one or more database queries, and how to access that data after it is loaded into the
DataSet object.

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 7.0, SQL Server 2000, or Microsoft Data Engine 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)

Filling a DataSet
Using a variety of objects from within the System.Data namespace, you can connect to a database
server, run a query, and have the results placed into a DataSet object. The DataSet is a disconnected
object. Therefore, after the data is loaded, the connection to the database is no longer used until you
want to load more data or update the server with the changes you have made to your in-memory
copy of the information.
To load data from a database into a DataSet, follow these steps:
1. Start Visual Studio .NET.
2. Create a new Console Application project in Microsoft Visual Basic .NET. Visual Studio .NET
creates a Module for you, along with an empty Main procedure.
3. Make sure that the project references the System and System.Data namespaces.
4. Use the Imports statement on the System, System.Data, 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 before any other declarations.

Imports System
Imports System.Data
Imports System.Data.SqlClient

5. The first step to get data from the database to the DataSet is to establish a database
connection, which requires a System.Data.SqlClient.SqlCommand object and a connection
string. The connection string in the code to follow connects a SQL Server server that is located
on the local computer (the computer where the code is running). You must modify this
connection string as appropriate for your environment. After the SqlConnection object is
created, call the Open method of that object to establish the actual database link.

Dim sConnectionString As String


sConnectionString = "Password=<strong password>;User ID=<usern
ame>;" & _
"Initial Catalog=pubs;" & _
"Data Source=(local)"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()

6. Create a DataAdapter object, which represents the link between the database and your DataSet
object. You can specify SQL or another type of command that is used to retrieve data as part of
the constructor object of the DataAdapter. This sample uses a SQL statement that retrieves
records from the Authors table in the Pubs database.

Dim daAuthors As _
New SqlDataAdapter("Select * From Authors", objConn)

7. You must declare and create an instance of a DataSet object, at which time you can supply a
name for the entire DataSet before you can start to load any data. The name may contain
several distinct tables.

Dim dsPubs As New DataSet("Pubs")

8. The SqlDataAdapter class provides two methods, Fill and FillSchema, that are crucial to loading
this data. Both of these methods load information into a DataSet. Fill loads the data itself, and
FillSchema loads all of the available metadata about a particular table (such as column names,
primary keys, and constraints). A good way to handle the data loading is to run FillSchema
followed by Fill. For example:

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


daAuthors.Fill(dsPubs, "Authors")

If you only use Fill, you can only load the basic metadata that is required to describe the
column names and data types. The Fill method does not load primary key information. To
change this default behavior, you can set the MissingSchemaAction property of the
DataAdapter object to MissingSchemaAction.AddWithKey, which loads the primary key
metadata along with the default information. For example:

daAuthors.MissingSchemaAction = MissingSchemaAction.AddWithKey
daAuthors.Fill(dsPubs, "Authors")

9. The data is now available as an individual DataTable object within the Tables collection of the
DataSet. If you specified a table name in the calls to FillSchema and Fill, you can use that name
to access the specific table that you want.

Dim tblAuthors As DataTable


tblAuthors = dsPubs.Tables("Authors")

10. You can use a For Each loop to loop through all of the DataRow objects within the Rows
collection of a DataTable. This gives you access to each row of the table. You can access
columns by name or by positional index (with '0' being the first column position). For example:

Dim drCurrent As DataRow

For Each drCurrent In tblAuthors.Rows


Console.WriteLine("{0} {1}", _
drCurrent("au_fname").ToString, _
drCurrent("au_lname").ToString)
Next
Console.ReadLine()

11. Save your project. On the Debug menu, click Start to run your project and make sure that it
works.

Complete code listing


Note: You will need to change User ID <username> and password =<strong password> to the
correct values before you run this code. Be sure that User ID has the appropriate permissions to
perform this operation on the database.

Option Explicit On
Option Strict On
Imports System
Imports System.Data
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim sConnectionString As String
sConnectionString = "Password=<strong password>;User ID=<us
ername>;" & _
"Initial Catalog=pubs;" & _
"Data Source=(local)"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim daAuthors As _
New SqlDataAdapter("Select * From Authors", objConn)
Dim dsPubs As New DataSet("Pubs")
daAuthors.FillSchema(dsPubs, SchemaType.Source, "Authors")
daAuthors.Fill(dsPubs, "Authors")
Dim tblAuthors As DataTable
tblAuthors = dsPubs.Tables("Authors")

Dim drCurrent As DataRow


For Each drCurrent In tblAuthors.Rows
Console.WriteLine("{0} {1}", _
drCurrent("au_fname").ToString, _
drCurrent("au_lname").ToString)
Next
Console.ReadLine()
End Sub
End Module

REFERENCES
For more information about ADO.NET, DataSet objects, and SQL, refer to the following Microsoft
Web sites:
"Diving into Data Access" (an MSDN Voices column by Dino Esposito)
http://msdn2.microsoft.com/en-us/library/ms810293.aspx
ADO.NET for the ADO Programmer
http://msdn2.microsoft.com/en-us/library/ms973217.aspx
MSDN Online .NET Framework Developer Center
http://msdn2.microsoft.com/en-us/netframework/default.aspx
For more information, see the following topics in the Visual Studio .NET Help documentation or the
following Microsoft Web sites:
Walkthrough: Creating a Distributed Application
http://msdn.microsoft.com/en-us/library/1as0t7ff.aspx
Walkthrough: Creating a Master-Detail Windows Form
http://msdn.microsoft.com/en-us/library/aa984462.aspx
If you installed the QuickStart samples, sample projects are available in the following directory:
C:\Program Files\Microsoft.NET\FrameworkSDK\Samples

Properties
Article ID: 301216 - Last Review: 12/06/2015 03:15:22 - Revision: 3.7

Applies to
Microsoft ADO.NET 1.0, Microsoft Visual Basic .NET 2002 Standard Edition
Keywords:
kbnosurvey kbarchive kbhowtomaster KB301216

Support

Security

Contact Us

# English (United States)


Terms of use

Privacy & cookies

Trademarks

2016 Microsoft

Anda mungkin juga menyukai