SlideShare a Scribd company logo
1 of 24
Simple ADO.NET program with Visual Studio .NET IDE
You just saw an example of working with an access 2000 database in my previous article. For
variety you'll see one example of a SQL server database. In this example, you'll take a different
approach. Instead of writing a console-based application, this time you'll create a windows
forms application and use the VS .NET IDE.
This sample application uses the SQL server Puran database. You read data from the Student
table.
Begin your first ADO.NET application by launching VS.NET and creating a new project using
File > New > Project. Choose the C# Windows Application template shown in Figure and type in
your project's name.
Figure: Creating a new C# windows application
Displaying data in a DataGrid control is the simplest task. In this sample, you'll show the Student
table data in a DataGrid control.
Clicking OK bring up the blank Form View. Drag a DataGrid control from the Toolbox > Window
forms onto the form and size it. Also drag a button onto the form and assign it a text property of
fill (see figure below).
Figure: Windows form controls for your first ADO .NET application
Now you are ready to write some ADO.NET code. In the first example you'll fill your DataGrid
using the SQL data provider. This is certainly the most efficient choice of data providers for
talking to a SQL server database. First you need to make sure you've imported all the proper
namespaces for using ADO.NET and this particular data provider this is code you'll need at the
top of the form code to bring in ADO.NET and the SQL server data provider
using System.Data; // dataset and related classes
using System.Data.SqlClient; // sql server data provider classes
Next, double-click on the Fill button to create the code for the event handler for this button.
You'll implement your ADO.NET routine inside this method. In order to retrieve data form the
database, you first need to connect to the database using a Connection object. The code in
listing below sets up the Connection object to the Puran database. The server in this example is
local host.
Listing: Constructing the Sql Server connection object
private void button1_Click(object sender, EventArgs e)
{
//Create a Connection object
string ConnectionString = "initial catalog=puran; data
source=MEHRASSQLSERVER2005; integrated security=sspi";
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = ConnectionString;
}
Note: If you using a remote server, than you need to pass the server name, user ID and
password in the connection string.
We have not yet connection to the database. This is done through the SqlDataAdapter object.
The DataAdapter is the bridge between the DataSource (sql) and the DataSet (memory). The
DataAdapter will be constructed with two elements in this example: a SQL SELECT command
to tell the DataAdapter which data to extract into the Dataset and the Connection object to tell
the DataAdapter how to connect into the data source. In this example, you select all the date
from the Student table. The DataAdapter is constructed below in listing. As you can see from
listing the sql string is a SELECT statement.
Listing: Constructing the Data Adapter
// Creating a SQL string and data adapter object
string sql = "select * from Student";
SqlDataAdapter myAdapter = new SqlDataAdapter(sql, myConnection);
Now you are ready to use the DataAdapter to transfer the desired data from the Student table
into a DataSet. To transfer the data, simply construct the DataSet and call the Fill method of the
DataAdapter on the DataSet to fill it with the Student table.
See Listing.
Listing: Constructing the Dataset and filling it
// Creating a SQL string and data adapter object
string sql = "select * from Student";
SqlDataAdapter myAdapter = new SqlDataAdapter(sql, myConnection);
// Construct the dataset and fill it
DataSet myDataSet = new DataSet("Student");
myAdapter.Fill(myDataSet, "Student");
Finally, you want to display the data from the Student table to the DataGrid control. You can do
this simply binding the DataSet to the Data Grid through its DefaultViewManager by using
DataGrid's DataSource property. You just set DataSource property of the Dataset's
DefaultViewManager. For example:
// Bind the List box to the Dataset
dataGrid1.DataSource = myDataSet.DefaultViewManager;
The final listing of the event handler method looks like listing below.
Listing: Binding the Dataset to the DataGrid Control
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Ado_tesst1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Create a Connection object
string ConnectionString = "initial catalog=puran; data
source=MEHRASSQLSERVER2005; integrated security=sspi";
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = ConnectionString;
// Creating a SQL string and data adapter object
string sql = "select * from Student";
SqlDataAdapter myAdapter = new SqlDataAdapter(sql, myConnection);
// Construct the dataset and fill it
DataSet myDataSet = new DataSet("Student");
myAdapter.Fill(myDataSet, "Student");
// Bind the List box to the Dataset
dataGrid1.DataSource = myDataSet.DefaultViewManager;
}
}
}
Now compile and run the project. Click the Fill button. The output of the program looks like
figure below.
Figure: Output of ADO .NET application in a Data Grid control
CAUTION: Make sure your SQL server is up and running. If SQL server is not running you'll get
an exception look like figure below.
Figure: Exception when SQL server is not running
Conclusion
Hope this article would have helped you in understanding writing a Simple ADO.NET program
with Visual Studio .NET IDE. See my other articles on the website on ADO.NET.
How to connect to a database and run a
command by using ADO.NET and Visual
Basic .NET
 Email
 Print
This article was previously published under Q301075
For a Microsoft Visual C# .NET version of this article, see 306636.
For a Microsoft Visual J# .NET version of this article, see 322045.
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.Data
 System.Data.SqlClient
IN THIS TASK
 SUMMARY

 Requirements
 How to run a command
 How to use parameters
 Complete code listing
 REFERENCES
Summary
This article describes how to use ADO.NET to connect to a database and to run a command
(such as the UPDATE, the INSERT, or the DELETE command) by using a Visual Basic .NET
console application.
Requirements
The following list outlines the recommended hardware, software, network infrastructure,
and service packs that are required:
 Microsoft Windows XP, Microsoft Windows Server 2003, Microsoft Windows 2000
Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or
Microsoft Windows NT 4.0 Server
 Microsoft Visual Studio .NET
This article assumes that you are familiar with the following topics:
 Database terminology
 Structured Query Language (SQL)
How to run a command
Commands are issued against databases to take actions against data stores and to include
any statement that can be issued against a database. You can use the OleDbCommand or
the SqlCommand classes to get a command to your data store, and OleDbCommand can
be specific to the data store. This article demonstrates both the SqlClient class (to connect
to a computer that is running Microsoft SQL Server) and the OleDb class (for any database
that has an OLE DB or ODBC driver available) within ADO.NET. However, the code is
generally the same for both.
With ADO, you can issue commands through the Command, the Connection, or
the Recordset object. In ADO.NET, only the Commandobjects
(SqlCommand or OleDbCommand) run commands.
To run a command, follow these steps:
1. Follow these steps to create a new console application in Visual Basic .NET:
a. Start Visual Studio .NET.
b. On the File menu, point to New, and then click Project.
c. In the New Project dialog box, click Visual Basic Projects under Project Types, and then
click Console Application underTemplates.
2. Make sure that your project contains a reference to the System.Data namespace, and add a
reference if it does not.
3. Use the Imports statement on the System and System.Data namespaces so that you do
not have to qualify declarations in those namespaces later in your code. You can also
include System.Data.SqlClient or System.Data.OleDb, depending on which one you are
using.
4.
5. Imports System
6. Imports System.Data
7. Imports System.Data.SqlClient
8. Before you can create a connection to a database, you must have a connection string.
Connection strings contain all of the information that you need to establish a database
connection, including the server name, the database name, the user ID, and the password.
For example, the following connection string points to a local computer that is running SQL
Server with a strong password for the <username> account:
For OleDb connections:
9.
10. Provider=SQLOLEDB.1;User ID=<username>;Password=<strong password>;Initial Catalog=pub
s;Data Source=(local)
For SqlClient connections:
User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Data Source=(local
)
NOTE: If you need more assistance determining the connection string for your database,
search for "ConnectionString" in the Microsoft Developer Network (MSDN) Library at the
following Microsoft Web site:
http://msdn.microsoft.com/en-us/search/default.aspx
11. Visual Studio creates a module and an empty Main() procedure. Declare a string variable,
and store the appropriate connection string for your database in this procedure:
12.
13. Sub Main()
14. Dim sConnectionString As String _
15. = "User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Data So
urce=(local)"
16. End Sub
17. Using this connection string, create a new OleDbConnection or SqlConnection object, and
call its Open method to establish a connection to your database:
18.
19. Dim objConn As New SqlConnection(sConnectionString)
20. objConn.Open()
21. Create a SqlCommand or OleDbCommand object, and pass in the command that you want
to run and the connection object that you created in the previous step. The following
sample code passes in the INSERT statement:
22.
23. Dim sSQL As String = "INSERT INTO Employee " & _
24. "(emp_id, fname, minit, lname, job_id, job_lvl, pub_id, hire_date)" & _
25. "VALUES ('MSD12923F', 'Duncan', 'W', 'Mackenzie', " & _
26. "10, 82,'0877','2001-01-01')"
27. Dim objCmd As New SqlCommand(sSQL, objConn)
28. After you create the SqlCommand or the OleDbCommand object, you can call
the ExecuteNonQuery method to run the command that it
represents. ExecuteNonQuery is designed for commands that do not return any results
(such as the DELETE, the UPDATE, and the INSERT statements). If the Execute statement
runs without throwing an exception (see the following code), the command has been
executed successfully against the database.
29.
30. objCmd.ExecuteNonQuery()
31. Save your project. On the Debug menu, click Start to run your command against the
database.
How to use parameters
When you run commands against a database (such as the UPDATE, the INSERT, and the
DELETE statements or calls to stored procedures), these commands are frequently
parameterized. This allows the command to be created one time but executed multiple
times with different values that are inserted instead of parameters. Consider the
corresponding DELETE statement to the INSERT statement that is used in the previous
section:
Dim sSQL As String = "DELETE FROM Employee WHERE emp_id = @emp_id"
The parameter name ("@emp_id") in this DELETE statement represents a parameter than
you can replace with different values each time you run the command.
To use parameters with your command, follow these steps:
1. Create your OleDbConnection or SqlConnection object, as you did in the "How to Run a
Command" section.
2. Replace the values with placeholders (for example, "@emp_id" or "@fname") so that your
command text uses parameters. See the DELETE statement before these steps for an
example.
3. Create your OleDbCommand or SqlCommand object, and pass in the connection object
that you created in the first step and the command text that contains the parameter
placeholders.
4. For each parameter, add a parameter object to the command object's parameters collection.
For each parameter, you must specify a name and data type.
5.
6. objCmd.Parameters.Add("@emp_id", SqlDbType.Char, 9)
7. Stored procedures can have parameters that return values and output parameters. You must
also set a value for each input parameter before you can run the query:
8.
9. objCmd.Parameters.Item("@emp_id").Value = "MSD12923F"
10. Run the query as follows:
11.
12. Try
13. objCmd.ExecuteNonQuery()
14. Console.WriteLine("Record Deleted")
15. Catch e As Exception
16. Console.WriteLine(e.ToString)
17. End Try
18. Console.WriteLine("Record Deleted")
19. Console.Read()
Complete code listing
Imports System
Imports System.Data
Imports System.Data.SqlClient
Module Module1
Sub Main()
AddRecord()
RemoveRecord()
Pause()
End Sub
Sub Pause()
Console.WriteLine("Press Enter To Continue...")
Console.ReadLine()
End Sub
Sub AddRecord()
Dim sConnectionString As String _
= "User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Dat
a Source=(local)"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim sSQL As String = "INSERT INTO Employee " & _
"(emp_id, fname, minit, lname, job_id, job_lvl, pub_id, hire_date)" & _
"VALUES ('MSD12923F', 'Duncan', 'W', 'Mackenzie', " & _
"10, 82,'0877','2001-01-01')"
Dim objCmd As New SqlCommand(sSQL, objConn)
Try
objCmd.ExecuteNonQuery()
Catch e As Exception
Console.WriteLine(e.Message)
End Try
Console.WriteLine("Record Added")
End Sub
Sub RemoveRecord()
Dim sConnectionString As String _
= "User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Dat
a Source=(local)"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim sSQL As String = "DELETE FROM Employee WHERE emp_id = @emp_id"
Dim objCmd As New SqlCommand(sSQL, objConn)
objCmd.Parameters.Add("@emp_id", SqlDbType.Char, 9)
objCmd.Parameters.Item("@emp_id").Value = "MSD12923F"
Try
objCmd.ExecuteNonQuery()
Console.WriteLine("Record Deleted")
Catch e As Exception
Console.WriteLine(e.ToString)
End Try
Console.WriteLine("Record Deleted")
Console.ReadLine()
End Sub
End Module
ADO.NET for the ADO
Programmer
Doug Rothaus
Mike Pizzo
Microsoft Corporation
December 2001
Summary: This article presents an overview of the data access architecture available through ADO.NET,
and answers the questions mostly commonly asked by developers familiar with ADO. (11 printed pages)
Contents
Introduction
Overview
The Design of ADO
ADO.NET: Explicit and Factored
Data Types
Summary
FAQ
What happened to the Recordset?
What happened to cursors?
How do I populate a DataSet with data from my database if it is disconnected from the data source?
How do I resolve changes to the DataSet back to the database?
How do I use ADO.NET with XML, similar to adPersistXml?
How do I use my existing COM components, which use ADO for data retrieval and updates, in the .NET
Framework?
Introduction
In the .NET Framework, Microsoft introduces ADO.NET, an evolution of the data access architecture
provided by the Microsoft® ActiveX® Data Objects (ADO) programming model. ADO.NET does not
replace ADO for the COM programmer; rather, it provides the .NET programmer with access to relational
data sources, XML, and application data. ADO.NET supports a variety of development needs, including the
creation of database clients and middle-tier business objects used by applications, tools, languages, and
Internet browsers.
Built with the ADO programmer in mind, ADO.NET contains many similarities to ADO, and also introduces
several new concepts in its design. This article addresses the most common questions the ADO
programmer encounters when first examining ADO.NET.
Overview
From its inception, ADO has provided an efficient, robust interface for COM programmers to work with
data. ADO is widely used as an interface to a variety of different stores because it can be called from any
automation language including Microsoft Visual Basic® 6.0, Microsoft Visual C++®, and a variety of
scripting interfaces.
ADO.NET is an evolution of ADO that provides better platform interoperability and scalable data access.
Creating a new set of data access APIs in ADO.NET offered the following advantages over directly porting
ADO to the .NET Framework.
Improved integration with XML: Subsequent to the design of ADO, XML began to play an increasingly
significant role in the design of applications. ADO.NET was designed from the ground up to integrate with
XML, and leverages XML in a fundamental way. In addition to persisting and loading both data and its
relational structure as XML, ADO.NET relies on XML for remoting data between tiers or clients. The generic
XML representation that ADO.NET uses provides a convenient method for transmitting data across any
network, including those with restrictive security perimeters. ADO.NET also uses XML tools to perform
validation, hierarchical queries, and data transformations on relational data.
Integration with the .NET Framework: ADO constructs, such as the Recordset, do not employ familiar
programming constructs but instead are modeled to be database-oriented. For example, cursors, which
are used to navigate and retrieve data, function differently than other data constructs such as arrays and
collections. In ADO.NET, however, in-memory data can be exposed through common .NET Framework
structures, including arrays and collections, providing you with common access methods when working
with relational data.
Improved support for the disconnected business model: ADO provides limited support for
disconnected access using the Recordset. ADO.NET introduces a new object, the DataSet, which serves as
a common, in-memory representation of relational data. The DataSet is, by design, disconnected at all
times. Because it holds no persistent connection to outside resources, it is ideal for packaging,
exchanging, caching, persisting, and loading data.
Explicit control of data access behaviors: The design of ADO includes implicit behaviors that may not
always be required in an application and that may therefore limit performance. ADO.NET provides well-
defined, factored components with predictable behavior, performance, and semantics that enable you to
address common scenarios in a highly optimized manner.
Improved design-time support: ADO derives information about data implicitly at run time, based on
metadata that is often expensive to obtain. ADO.NET, on the other hand, leverages known metadata at
design time in order to provide better run-time performance and more consistent run-time behavior.
The Design of ADO
To better understand the model and design of ADO.NET, it is helpful to review some of the core aspects
of ADO.
ADO uses a single object, the Recordset, as a common representation for working with all types of data.
The Recordset is used for working with a forward-only stream of results from a database, for scrolling
through data held on a server, or for scrolling through a set of cached results. Changes made to data may
be applied immediately to the database, or applied as a batch using optimistic search and update
operations. You specify the desired functionality when you create the Recordset, and the behavior of the
resulting Recordset can vary greatly depending on the properties you request.
Because ADO uses a single object that can behave in many different ways, it enables you to keep the
object model of your applications very simple. However, it is difficult to write common, predictable, and
optimized code because the behavior, performance, and semantics exhibited by that single object can
vary greatly depending on how the object is generated and what data it is accessing. This is particularly
true for generic components (such as a grid control) that attempt to consume data not generated by the
component and for which the component has no ability to specify required behavior or functionality.
ADO.NET: Explicit and Factored
In designing ADO.NET, consideration was given to the tasks that developers commonly face when
accessing and working with data. Rather than using a single object to perform a number of tasks,
ADO.NET factors specific functionality into explicit objects that are optimized to enable developers to
accomplish each task.
The functionality that the ADO Recordset provides has been factored into the following explicit objects in
ADO.NET: theDataReader, which provides fast, forward-only, read-only access to query results;
the DataSet, which provides an in-memory relational representation of data; and the DataAdapter, which
provides a bridge between the DataSet and the data source. The ADO.NET Command object also
includes explicit functionality such as the ExecuteNonQuery method for commands that do not return
rows, and the ExecuteScalar method for queries that return a single value rather than a row set.
To better understand how the design of ADO.NET is made up of objects that are optimized to perform
explicit behavior, consider the following tasks that are common when working with data.
Forward-Only Read-Only Data Streams
Applications, particularly middle-tier applications, often process a series of results programmatically,
requiring no user interaction and no updating of or scrolling back through the results as they are read. In
ADO, this type of data retrieval is performed using a Recordset with a forward-only cursor and a read-only
lock. In ADO.NET, however, the DataReaderobject optimizes this type of data retrieval by providing a
non-buffered, forward-only, read-only stream that provides the most efficient mechanism for retrieving
results from the database. Much of this efficiency is gained as a result of theDataReader having been
designed solely for this purpose, without having to support scenarios where data is updated at the data
source or cached locally as with the ADO Recordset.
Returning a Single Value
Often the only data to be retrieved from a database is a single value (for example, an account balance). In
ADO, you perform this type of data retrieval by creating a Recordset object, reading through the results,
retrieving the single value, and then closing the Recordset. In ADO.NET, however, the Command object
supports this function through theExecuteScalar method, which returns the single value from the
database without having to introduce an additional object to hold the results.
Disconnected Access to Data
A frequent case for exposing data is a representation in which a user can navigate the data in an ad-hoc
manner without holding locks or tying up resources on the server. Some examples of this scenario are
binding data to a control or combining data from multiple data sources and/or XML. The ADO Recordset
provides some support for these scenarios, using a client-side cursor location. However, in ADO.NET
the DataSet is explicitly designed for such tasks.
The DataSet provides a common, completely disconnected data representation that can hold results from
a variety of different sources. Because the DataSet is completely independent of the data source, it
provides the same performance and semantics regardless of whether the data is loaded from a database,
loaded from XML, or is generated by the application. A single DataSet may contain tables populated from
several different databases and other non-database sources; to the consumer of the DataSet it all looks
and behaves exactly the same. Within the DataSet you can define relations to navigate from a table
populated from one database (for example, "Customers"), to a related table populated from an entirely
different database (for example, "Orders"), and from there to a third table (for example, "OrderDetails")
containing values loaded from XML. The relational capabilities of the DataSet provide an advantage over
the Recordset, which is limited to exposing the results from multiple tables either as a single joined result,
or by returning multiple distinct result sets, requiring the developer to handle and relate the results
manually. Though the Recordset has the ability to return and navigate hierarchical results (using the
MSDataShape provider), the DataSet provides much greater flexibility when dealing with related result
sets. The DataSet also provides the ability to transmit results to and from a remote client or server in an
open XML format, with the schema defined using the XML Schema definition language (XSD).
Retrieving and Updating Data from a Data Source
Based on customer feedback and common use cases it is clear that in most application development
scenarios (with the exception of ad-hoc tools and generic data components) the developer knows certain
things about the data at design time that technologies like ADO attempt to derive at run time. For
example, in most middle-tier applications the developer knows, at the time of application development,
the type of database to be accessed, what queries will be executed, and how the results will be returned.
ADO.NET gives you the ability to apply this knowledge at design time in order to provide better run-time
performance and predictability.
As an example, when using batch updating with ADO Recordset objects, you must submit changes to the
database by executing appropriate INSERT, UPDATE, and DELETE statements for each row that has
changed. ADO generates these statements implicitly, at run time, based on metadata that is often
expensive to obtain. ADO.NET, however, enables you to explicitly specify INSERT, UPDATE, and DELETE
commands, as well as custom business logic such as a stored procedure, that will be used to resolve
changes in a DataSet back to the data source using the DataAdapter. This model provides you with
greater control over how application data is returned and updated, and removes the expense of gathering
the metadata at run time.
The DataAdapter provides the bridge between the DataSet and the data source. A DataAdapter is used
to populate aDataSet with results from a database, and to read changes out of a DataSet and resolve
those changes back to the database. Using a separate object, the DataAdapter, to communicate with the
database allows the DataSet to remain completely generic with respect to the data it contains, and gives
you more control over when and how commands are executed and changes are sent to the database.
ADO performs much of this behavior implicitly, however the explicit design of ADO.NET enables you to
fine-tune your interaction with a data source for best performance and scalability.
The implicit update behavior of ADO is also available in ADO.NET using a CommandBuilder object that,
based on a single table SELECT, automatically generates the INSERT, UPDATE, and DELETE commands
used for queries by theDataAdapter. However, the compromise for this convenience is slower
performance and less control over how changes are propagated to the data source because, as with ADO,
the commands are generated from metadata collected at run time.
Data Types
In ADO, all results are returned in a standard OLE Automation Variant type. This can hinder performance
because, in addition to conversion overhead, variants are allocated using task-allocated system memory,
which causes contention across the system. When retrieving results from a DataReader in ADO.NET,
however, you can retrieve columns in their native data type, as a common Object class, without going
through expensive conversions. Data values can either be exposed as .NET Framework types, or can be
placed in a proprietary structure in the .NET Framework to preserve the fidelity of the native type. An
example of this is the SQL Server .NET Data Provider, which can be used to expose Microsoft® SQL
Server™ data as .NET Framework types, or as proprietary types defined by the classes in
theSystem.Data.SqlTypes namespace.
Summary
ADO.NET is designed to build on the strength of the ADO programming model, while providing an
evolution of data access technology to meet the changing needs of the developer. It is designed to
leverage your existing knowledge of ADO, while giving you much finer control over the components,
resources, and behavior of your applications when accessing and working with data.
Related Topics in the .NET Framework SDK
 Accessing Data with ADO.NET
Describes ADO.NET architecture and how to use the ADO.NET classes to manage application data
and interact with data sources including Microsoft SQL Server, OLE DB, and XML.
 Overview of ADO.NET
Provides an introduction to the design and components of ADO.NET.
 Using .NET Data Providers to Access Data
Describes the components of a .NET data provider and how to use them to access relational data
sources.
 Creating and Using DataSets
Describes the DataSet and how to use it to manage relational data in your application.
 XML and the DataSet
Describes how the DataSet interacts with XML as a data source, including loading and persisting
the contents of a DataSet as XML and synchronizing a DataSet with an XmlDataDocument.
FAQ
This section answers the questions most commonly asked by developers familiar with ADO as they begin
to familiarize themselves with ADO.NET.
What happened to the Recordset?
The ADO Recordset bundles functionality together into one object and handles much behavior implicitly.
ADO.NET, on the other hand, has been designed to factor behavior into separate components and to
enable you to explicitly control behavior. The following table describes the individual ADO.NET objects
that provide the functionality of the ADO Recordset.
ADO.NET object Description
DataReader Providesaforward-only,read-onlystreamof datafroma data source.
The DataReader is similar to a Recordset with CursorType =
adOpenForwardOnly and LockType = adLockReadOnly.
DataSet Providesin-memoryaccesstorelationaldata.
The DataSet is independent of any specific data source and
therefore can be populated from multiple and differing data
sources including relational databases and XML, or can be
populated with data local to the application. Data is stored in a
collection of one or more tables, and can be accessed non-
sequentially and without limits to availability, unlike ADO in
which data must be accessed a single row at a time.
A DataSet can contain relationships between tables, similar to the
ADO Recordset in which a single result set is created from a
JOIN. A DataSet can also contain unique, primary key, and
foreign key constraints on its tables.
The DataSet is similar to a Recordset with CursorLocation =
adUseClient,CursorType = adOpenStatic, and LockType =
adLockOptimistic. However, the DataSet has extended
capabilities over the Recordset for managing application data.
DataAdapter PopulatesaDataSet withdata froma relational database andresolves
changesinthe DataSet back to the data source.
The DataAdapter enables you to explicitly specify behavior that
the Recordset performs implicitly.
Related Topics in the .NET Framework SDK
 Retrieving Data Using the DataReader
Describes the DataReader and how to use it to return results from a data source.
 Creating and Using DataSets
Describes the DataSet and how to use it to manage relational data in your application.
 Populating a DataSet from a DataAdapter
Describes how to fill the contents of a DataSet from a relational data source using
a DataAdapter.
 Updating the Database with a DataAdapter and the DataSet
Describes how to resolve changes to data in a DataSet back to a data source using
a DataAdapter.
 Using .NET Data Providers to Access Data
Describes the components of a .NET data provider and how to use them to access relational data
sources.
What happened to cursors?
In ADO it is possible, within a common Recordset object, to request multiple and differing cursor types
(dynamic, keyset, static, and forward-only) with different properties that define how the cursor behaves,
for example whether the cursor is updateable or is read-only, or whether it is implemented on the client
or on the server. In ADO.NET, however, different classes are exposed that give you greater control over
each type of interaction. The DataReader provides an extremely fast, forward-only, read-only cursor on
the server side that enables you to retrieve a stream of results from a database. The DataSet provides a
completely disconnected "client" cursor, through which you can scroll and update, that is equivalent to
the static cursor in ADO. These objects, along with the DataAdapter that enables you to move data
between the DataSet and a database, provide you with optimal access methods for the most common
types of data interactions.
Note that ADO.NET version 1.0 does not expose a scrollable, updateable server-side cursor. Applications
that require scrolling and positioned updates on the client side generally involve user interaction. Because
server-side cursors require state to be held on the server, your application will not be robust or scalable if
it must hold those valuable resources while users interact with the data on the client side. Most
applications that currently use scrollable server-side cursors on the client could be much more efficiently
written according to one of the following designs:
 Use stored procedures to handle custom logic, to run on the server instead of the client.
 Use a forward-only, read-only cursor to return data from the server, and execute commands to
process any updates.
 Populate a DataSet with results, modify the data locally, and then propagate those changes back
to the server.
Related Topics in the .NET Framework SDK
 Using .NET Data Providers to Access Data
Describes the components of a .NET data provider and how to use them to access relational data
sources.
 Optimistic Concurrency
Describes the optimistic concurrency model and how to use ADO.NET to handle optimistic
concurrency violations.
 Paging Through a Query Result
Provides an example of returning the results of a query as smaller sections, or "pages", of data.
How do I populate a DataSet with data from my database if it is disconnected
from the data source?
How do I resolve changes to the DataSet back to the database?
The DataAdapter provides the bridge between the DataSet and the data source. You control the
behavior for populating the DataSet and resolving inserts, updates, and deletes in the DataSet back to
the data source by defining explicit commands that the DataAdapter will use.
The DataAdapter command properties are the SelectCommand, InsertCommand, UpdateCommand,
andDeleteCommand. Each command corresponds directly to a SELECT, INSERT, UPDATE, and DELETE
action at the data source. Additionally, these actions can be optimized as a stored procedure call. Once
the DataAdapter commands have been defined, you can pass a DataSet to the Fill method of
a DataAdapter to fill a DataSet with the results returned by the SelectCommand, or pass a DataSet to
the Update method of a DataAdapter to propagate changes in the DataSetback to the data source.
The InsertCommand will process rows that have been added to the DataSet. TheUpdateCommand will
process existing rows that have been modified in the DataSet. The DeleteCommand will process existing
rows that have been deleted from the DataSet.
Related Topics in the .NET Framework SDK
 Updating the Database with a DataAdapter and the DataSet
Describes how to resolve changes to data in a DataSet back to a data source using
a DataAdapter.
 Populating a DataSet from a DataAdapter
Describes how to fill the contents of a DataSet from a relational data source using
a DataAdapter.
 Using .NET Data Providers to Access Data
Describes the components of a .NET data provider and how to use them to access relational data
sources.
How do I use ADO.NET with XML, similar to adPersistXml?
The DataSet provides extensive support for using XML to load and persist the schema and data within
a DataSet. You can load the contents of the DataSet from any XML format, and write the contents of
a DataSet to an XML format that is much simpler and more generic than that of an ADO Recordset saved
as XML. The schema, or relational structure, of aDataSet can easily be persisted as, or created from, a
simple XML Schema definition language (XSD) schema. If an XML document has no XML Schema
supplied, and no schema is defined within the DataSet, the DataSet can infer the schema from the XML
elements in the XML document. Additionally, the DataSet gives you control over how rows and columns
are written to and read from an XML document. Columns can be mapped as attributes, elements, or
simple content, or can be hidden (not written out). Related rows can be nested within their parent
element, or treated as sibling elements.
The DataSet can also be synchronized with an XmlDataDocument to provide simultaneous relational
and hierarchical views of a single set of data. By synchronizing a DataSet with an XmlDataDocument,
you also gain access to other XML functionality for the data in your DataSet such as the ability to perform
XML Path Language (XPath) queries over the data or to apply an Extensible Stylesheet Language
Transformation (XSLT transformation) to the data.
The SQL Server .NET Data Provider also provides the capability, using the SqlCommand, to return the
results of FOR XML queries against Microsoft SQL Server 2000 or later directly as an XmlReader.
In addition to the XML capabilities provided with ADO.NET, SQLXML 2.0 (XML for SQL Server 2000)
contains SQLXML Managed Classes that enable you to access the XML functionality of Microsoft SQL
Server 2000 and later from the .NET Framework. For example, these classes allow you to execute XML
templates, perform XPath queries over data at the server, or perform updates to data using Updategrams
or Diffgrams.
Related Topics in the .NET Framework SDK
 Obtaining Data as XML from SQL Server
Describes how to return the results of a FOR XML query in Microsoft SQL Server 2000 or later as
an XmlReaderusing the SQL Server .NET Data Provider.
 XML and the DataSet
Describes how the DataSet interacts with XML as a data source, including loading and persisting
the contents of a DataSet as XML and synchronizing a DataSet with an XmlDataDocument.
 SQLXML 2.0 (XML for SQL Server 2000)
Provides the release of XML for Microsoft SQL Server 2000 (SQLXML 2.0), which includes SQLXML
Managed Classes for use in the .NET Framework.
How do I use my existing COM components, which use ADO for data retrieval and
updates, in the .NET Framework?
COM components that return or consume ADO objects are available in the .NET Framework using COM
interop services. Additionally, the OLE DB .NET Data Provider includes overloads to
the OleDbDataAdapter.Fill method which take as input an ADO Recordset or Record object returned by
existing COM components, and populate a DataSet with the data contained in the ADO object. Updates
to the data in the DataSet can be propagated back to the data source using aDataAdapter. You can also
use an Extensible Stylesheet Language Transformation (XSLT transformation) to transform between the
XML format of the ADO Recordset and the XML format of the ADO.NET DataSet.
Related Topics in the .NET Framework SDK
 Accessing an ADO Recordset or Record from ADO.NET
Describes how to use the OleDbDataAdapter to fill the contents of a DataSet or DataTable from
an ADO Recordset or Record object.
 Exposing COM Components to the .NET Framework
Describes how to access COM components from within the .NET Framework.

More Related Content

What's hot

What's hot (20)

Dealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETDealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NET
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Ado.net
Ado.netAdo.net
Ado.net
 
Murach: How to use Entity Framework EF Core
Murach: How to use Entity Framework EF  CoreMurach: How to use Entity Framework EF  Core
Murach: How to use Entity Framework EF Core
 
For Beginers - ADO.Net
For Beginers - ADO.NetFor Beginers - ADO.Net
For Beginers - ADO.Net
 
ADO.NET -database connection
ADO.NET -database connectionADO.NET -database connection
ADO.NET -database connection
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Ado .net
Ado .netAdo .net
Ado .net
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
 
Ado.Net
Ado.NetAdo.Net
Ado.Net
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
ODI User and Security
ODI User and Security ODI User and Security
ODI User and Security
 
Disconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETDisconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NET
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookies
 
Ado.net
Ado.netAdo.net
Ado.net
 

Viewers also liked (18)

Programming
ProgrammingProgramming
Programming
 
Big data-and-the-web
Big data-and-the-webBig data-and-the-web
Big data-and-the-web
 
Cloudcomputing basics
Cloudcomputing basicsCloudcomputing basics
Cloudcomputing basics
 
Filtering content bbased crs
Filtering content bbased crsFiltering content bbased crs
Filtering content bbased crs
 
Knightstour
KnightstourKnightstour
Knightstour
 
Rational rose tutorial
Rational rose tutorialRational rose tutorial
Rational rose tutorial
 
Unit ii-ppt
Unit ii-pptUnit ii-ppt
Unit ii-ppt
 
Running your database in the cloud presentation
Running your database in the cloud presentationRunning your database in the cloud presentation
Running your database in the cloud presentation
 
Mobile development xamarain
Mobile development xamarainMobile development xamarain
Mobile development xamarain
 
Chapter 02 collaborative recommendation
Chapter 02   collaborative recommendationChapter 02   collaborative recommendation
Chapter 02 collaborative recommendation
 
Intelli j idea-report
Intelli j idea-reportIntelli j idea-report
Intelli j idea-report
 
7 embed systcasestudy
7 embed systcasestudy7 embed systcasestudy
7 embed systcasestudy
 
Android wear notes
Android wear notesAndroid wear notes
Android wear notes
 
(148065320) dijistra algo
(148065320) dijistra algo(148065320) dijistra algo
(148065320) dijistra algo
 
Running your database in the cloud presentation
Running your database in the cloud presentationRunning your database in the cloud presentation
Running your database in the cloud presentation
 
How to use sq lite with java using net beans
How to use sq lite with java using net beansHow to use sq lite with java using net beans
How to use sq lite with java using net beans
 
Javanotes5 linked
Javanotes5 linkedJavanotes5 linked
Javanotes5 linked
 
Apidays efficient-131204080056-phpapp02
Apidays efficient-131204080056-phpapp02Apidays efficient-131204080056-phpapp02
Apidays efficient-131204080056-phpapp02
 

Similar to Simple ado program by visual studio

Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAlfa Gama Omega
 
Once the Application has started up and you are at the Start Page, s.docx
Once the Application has started up and you are at the Start Page, s.docxOnce the Application has started up and you are at the Start Page, s.docx
Once the Application has started up and you are at the Start Page, s.docxarnit1
 
systems labOnce the Application has started up and you are at the .docx
systems labOnce the Application has started up and you are at the .docxsystems labOnce the Application has started up and you are at the .docx
systems labOnce the Application has started up and you are at the .docxperryk1
 
3-ADO.NET.pdf
3-ADO.NET.pdf3-ADO.NET.pdf
3-ADO.NET.pdfManalAg
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenSony Suci
 
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx        Greetings and Salutations.docxCIS407AWk2iLabDefault.aspx        Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docxclarebernice
 
ADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaSonu Vishwakarma
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...mauricemuteti2015
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to adoHarman Bajwa
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.netHemant Sankhla
 

Similar to Simple ado program by visual studio (20)

Ado.Net
Ado.NetAdo.Net
Ado.Net
 
unit 3.docx
unit 3.docxunit 3.docx
unit 3.docx
 
2310 b 09
2310 b 092310 b 09
2310 b 09
 
Ado Presentation
Ado PresentationAdo Presentation
Ado Presentation
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
 
Once the Application has started up and you are at the Start Page, s.docx
Once the Application has started up and you are at the Start Page, s.docxOnce the Application has started up and you are at the Start Page, s.docx
Once the Application has started up and you are at the Start Page, s.docx
 
systems labOnce the Application has started up and you are at the .docx
systems labOnce the Application has started up and you are at the .docxsystems labOnce the Application has started up and you are at the .docx
systems labOnce the Application has started up and you are at the .docx
 
3-ADO.NET.pdf
3-ADO.NET.pdf3-ADO.NET.pdf
3-ADO.NET.pdf
 
B_110500002
B_110500002B_110500002
B_110500002
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
 
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx        Greetings and Salutations.docxCIS407AWk2iLabDefault.aspx        Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
 
Sql server-function
Sql server-functionSql server-function
Sql server-function
 
ADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaADO .NET by Sonu Vishwakarma
ADO .NET by Sonu Vishwakarma
 
Lecture13
Lecture13Lecture13
Lecture13
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to ado
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.net
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
 

Recently uploaded

Call Us ✡️97111⇛47426⇛Call In girls Vasant Vihar༒(Delhi)
Call Us ✡️97111⇛47426⇛Call In girls Vasant Vihar༒(Delhi)Call Us ✡️97111⇛47426⇛Call In girls Vasant Vihar༒(Delhi)
Call Us ✡️97111⇛47426⇛Call In girls Vasant Vihar༒(Delhi)jennyeacort
 
Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025Rndexperts
 
Call Girls Aslali 7397865700 Ridhima Hire Me Full Night
Call Girls Aslali 7397865700 Ridhima Hire Me Full NightCall Girls Aslali 7397865700 Ridhima Hire Me Full Night
Call Girls Aslali 7397865700 Ridhima Hire Me Full Nightssuser7cb4ff
 
call girls in Harsh Vihar (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Harsh Vihar (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Harsh Vihar (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Harsh Vihar (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Service
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Service
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Servicejennyeacort
 
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`dajasot375
 
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证nhjeo1gg
 
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024CristobalHeraud
 
VIP Call Girls Service Kukatpally Hyderabad Call +91-8250192130
VIP Call Girls Service Kukatpally Hyderabad Call +91-8250192130VIP Call Girls Service Kukatpally Hyderabad Call +91-8250192130
VIP Call Girls Service Kukatpally Hyderabad Call +91-8250192130Suhani Kapoor
 
Untitled presedddddddddddddddddntation (1).pptx
Untitled presedddddddddddddddddntation (1).pptxUntitled presedddddddddddddddddntation (1).pptx
Untitled presedddddddddddddddddntation (1).pptxmapanig881
 
Housewife Call Girls NRI Layout - Call 7001305949 Rs-3500 with A/C Room Cash ...
Housewife Call Girls NRI Layout - Call 7001305949 Rs-3500 with A/C Room Cash ...Housewife Call Girls NRI Layout - Call 7001305949 Rs-3500 with A/C Room Cash ...
Housewife Call Girls NRI Layout - Call 7001305949 Rs-3500 with A/C Room Cash ...narwatsonia7
 
Call Girls Satellite 7397865700 Ridhima Hire Me Full Night
Call Girls Satellite 7397865700 Ridhima Hire Me Full NightCall Girls Satellite 7397865700 Ridhima Hire Me Full Night
Call Girls Satellite 7397865700 Ridhima Hire Me Full Nightssuser7cb4ff
 
Revit Understanding Reference Planes and Reference lines in Revit for Family ...
Revit Understanding Reference Planes and Reference lines in Revit for Family ...Revit Understanding Reference Planes and Reference lines in Revit for Family ...
Revit Understanding Reference Planes and Reference lines in Revit for Family ...Narsimha murthy
 
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130Suhani Kapoor
 
Design Portfolio - 2024 - William Vickery
Design Portfolio - 2024 - William VickeryDesign Portfolio - 2024 - William Vickery
Design Portfolio - 2024 - William VickeryWilliamVickery6
 
Introduction-to-Canva-and-Graphic-Design-Basics.pptx
Introduction-to-Canva-and-Graphic-Design-Basics.pptxIntroduction-to-Canva-and-Graphic-Design-Basics.pptx
Introduction-to-Canva-and-Graphic-Design-Basics.pptxnewslab143
 
2024新版美国旧金山州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
2024新版美国旧金山州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree2024新版美国旧金山州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
2024新版美国旧金山州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degreeyuu sss
 
Call Girls Meghani Nagar 7397865700 Independent Call Girls
Call Girls Meghani Nagar 7397865700  Independent Call GirlsCall Girls Meghani Nagar 7397865700  Independent Call Girls
Call Girls Meghani Nagar 7397865700 Independent Call Girlsssuser7cb4ff
 
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一lvtagr7
 

Recently uploaded (20)

Call Us ✡️97111⇛47426⇛Call In girls Vasant Vihar༒(Delhi)
Call Us ✡️97111⇛47426⇛Call In girls Vasant Vihar༒(Delhi)Call Us ✡️97111⇛47426⇛Call In girls Vasant Vihar༒(Delhi)
Call Us ✡️97111⇛47426⇛Call In girls Vasant Vihar༒(Delhi)
 
Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025
 
Call Girls Aslali 7397865700 Ridhima Hire Me Full Night
Call Girls Aslali 7397865700 Ridhima Hire Me Full NightCall Girls Aslali 7397865700 Ridhima Hire Me Full Night
Call Girls Aslali 7397865700 Ridhima Hire Me Full Night
 
call girls in Harsh Vihar (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Harsh Vihar (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Harsh Vihar (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Harsh Vihar (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Service
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Service
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Service
 
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`
 
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证
 
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024
 
VIP Call Girls Service Kukatpally Hyderabad Call +91-8250192130
VIP Call Girls Service Kukatpally Hyderabad Call +91-8250192130VIP Call Girls Service Kukatpally Hyderabad Call +91-8250192130
VIP Call Girls Service Kukatpally Hyderabad Call +91-8250192130
 
Untitled presedddddddddddddddddntation (1).pptx
Untitled presedddddddddddddddddntation (1).pptxUntitled presedddddddddddddddddntation (1).pptx
Untitled presedddddddddddddddddntation (1).pptx
 
Housewife Call Girls NRI Layout - Call 7001305949 Rs-3500 with A/C Room Cash ...
Housewife Call Girls NRI Layout - Call 7001305949 Rs-3500 with A/C Room Cash ...Housewife Call Girls NRI Layout - Call 7001305949 Rs-3500 with A/C Room Cash ...
Housewife Call Girls NRI Layout - Call 7001305949 Rs-3500 with A/C Room Cash ...
 
Call Girls Satellite 7397865700 Ridhima Hire Me Full Night
Call Girls Satellite 7397865700 Ridhima Hire Me Full NightCall Girls Satellite 7397865700 Ridhima Hire Me Full Night
Call Girls Satellite 7397865700 Ridhima Hire Me Full Night
 
Revit Understanding Reference Planes and Reference lines in Revit for Family ...
Revit Understanding Reference Planes and Reference lines in Revit for Family ...Revit Understanding Reference Planes and Reference lines in Revit for Family ...
Revit Understanding Reference Planes and Reference lines in Revit for Family ...
 
Cheap Rate ➥8448380779 ▻Call Girls In Iffco Chowk Gurgaon
Cheap Rate ➥8448380779 ▻Call Girls In Iffco Chowk GurgaonCheap Rate ➥8448380779 ▻Call Girls In Iffco Chowk Gurgaon
Cheap Rate ➥8448380779 ▻Call Girls In Iffco Chowk Gurgaon
 
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130
 
Design Portfolio - 2024 - William Vickery
Design Portfolio - 2024 - William VickeryDesign Portfolio - 2024 - William Vickery
Design Portfolio - 2024 - William Vickery
 
Introduction-to-Canva-and-Graphic-Design-Basics.pptx
Introduction-to-Canva-and-Graphic-Design-Basics.pptxIntroduction-to-Canva-and-Graphic-Design-Basics.pptx
Introduction-to-Canva-and-Graphic-Design-Basics.pptx
 
2024新版美国旧金山州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
2024新版美国旧金山州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree2024新版美国旧金山州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
2024新版美国旧金山州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
 
Call Girls Meghani Nagar 7397865700 Independent Call Girls
Call Girls Meghani Nagar 7397865700  Independent Call GirlsCall Girls Meghani Nagar 7397865700  Independent Call Girls
Call Girls Meghani Nagar 7397865700 Independent Call Girls
 
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一
 

Simple ado program by visual studio

  • 1. Simple ADO.NET program with Visual Studio .NET IDE You just saw an example of working with an access 2000 database in my previous article. For variety you'll see one example of a SQL server database. In this example, you'll take a different approach. Instead of writing a console-based application, this time you'll create a windows forms application and use the VS .NET IDE. This sample application uses the SQL server Puran database. You read data from the Student table. Begin your first ADO.NET application by launching VS.NET and creating a new project using File > New > Project. Choose the C# Windows Application template shown in Figure and type in your project's name. Figure: Creating a new C# windows application
  • 2. Displaying data in a DataGrid control is the simplest task. In this sample, you'll show the Student table data in a DataGrid control. Clicking OK bring up the blank Form View. Drag a DataGrid control from the Toolbox > Window forms onto the form and size it. Also drag a button onto the form and assign it a text property of fill (see figure below). Figure: Windows form controls for your first ADO .NET application Now you are ready to write some ADO.NET code. In the first example you'll fill your DataGrid using the SQL data provider. This is certainly the most efficient choice of data providers for talking to a SQL server database. First you need to make sure you've imported all the proper namespaces for using ADO.NET and this particular data provider this is code you'll need at the top of the form code to bring in ADO.NET and the SQL server data provider using System.Data; // dataset and related classes using System.Data.SqlClient; // sql server data provider classes
  • 3. Next, double-click on the Fill button to create the code for the event handler for this button. You'll implement your ADO.NET routine inside this method. In order to retrieve data form the database, you first need to connect to the database using a Connection object. The code in listing below sets up the Connection object to the Puran database. The server in this example is local host. Listing: Constructing the Sql Server connection object private void button1_Click(object sender, EventArgs e) { //Create a Connection object string ConnectionString = "initial catalog=puran; data source=MEHRASSQLSERVER2005; integrated security=sspi"; SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = ConnectionString; } Note: If you using a remote server, than you need to pass the server name, user ID and password in the connection string. We have not yet connection to the database. This is done through the SqlDataAdapter object. The DataAdapter is the bridge between the DataSource (sql) and the DataSet (memory). The DataAdapter will be constructed with two elements in this example: a SQL SELECT command to tell the DataAdapter which data to extract into the Dataset and the Connection object to tell the DataAdapter how to connect into the data source. In this example, you select all the date from the Student table. The DataAdapter is constructed below in listing. As you can see from listing the sql string is a SELECT statement. Listing: Constructing the Data Adapter // Creating a SQL string and data adapter object string sql = "select * from Student"; SqlDataAdapter myAdapter = new SqlDataAdapter(sql, myConnection); Now you are ready to use the DataAdapter to transfer the desired data from the Student table into a DataSet. To transfer the data, simply construct the DataSet and call the Fill method of the DataAdapter on the DataSet to fill it with the Student table. See Listing. Listing: Constructing the Dataset and filling it // Creating a SQL string and data adapter object string sql = "select * from Student";
  • 4. SqlDataAdapter myAdapter = new SqlDataAdapter(sql, myConnection); // Construct the dataset and fill it DataSet myDataSet = new DataSet("Student"); myAdapter.Fill(myDataSet, "Student"); Finally, you want to display the data from the Student table to the DataGrid control. You can do this simply binding the DataSet to the Data Grid through its DefaultViewManager by using DataGrid's DataSource property. You just set DataSource property of the Dataset's DefaultViewManager. For example: // Bind the List box to the Dataset dataGrid1.DataSource = myDataSet.DefaultViewManager; The final listing of the event handler method looks like listing below. Listing: Binding the Dataset to the DataGrid Control using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace Ado_tesst1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //Create a Connection object string ConnectionString = "initial catalog=puran; data source=MEHRASSQLSERVER2005; integrated security=sspi"; SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = ConnectionString; // Creating a SQL string and data adapter object string sql = "select * from Student";
  • 5. SqlDataAdapter myAdapter = new SqlDataAdapter(sql, myConnection); // Construct the dataset and fill it DataSet myDataSet = new DataSet("Student"); myAdapter.Fill(myDataSet, "Student"); // Bind the List box to the Dataset dataGrid1.DataSource = myDataSet.DefaultViewManager; } } } Now compile and run the project. Click the Fill button. The output of the program looks like figure below. Figure: Output of ADO .NET application in a Data Grid control CAUTION: Make sure your SQL server is up and running. If SQL server is not running you'll get an exception look like figure below.
  • 6. Figure: Exception when SQL server is not running Conclusion Hope this article would have helped you in understanding writing a Simple ADO.NET program with Visual Studio .NET IDE. See my other articles on the website on ADO.NET. How to connect to a database and run a command by using ADO.NET and Visual Basic .NET  Email  Print This article was previously published under Q301075 For a Microsoft Visual C# .NET version of this article, see 306636. For a Microsoft Visual J# .NET version of this article, see 322045. 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.Data  System.Data.SqlClient IN THIS TASK  SUMMARY 
  • 7.  Requirements  How to run a command  How to use parameters  Complete code listing  REFERENCES Summary This article describes how to use ADO.NET to connect to a database and to run a command (such as the UPDATE, the INSERT, or the DELETE command) by using a Visual Basic .NET console application. Requirements The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:  Microsoft Windows XP, Microsoft Windows Server 2003, Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or Microsoft Windows NT 4.0 Server  Microsoft Visual Studio .NET This article assumes that you are familiar with the following topics:  Database terminology  Structured Query Language (SQL) How to run a command Commands are issued against databases to take actions against data stores and to include any statement that can be issued against a database. You can use the OleDbCommand or the SqlCommand classes to get a command to your data store, and OleDbCommand can be specific to the data store. This article demonstrates both the SqlClient class (to connect to a computer that is running Microsoft SQL Server) and the OleDb class (for any database that has an OLE DB or ODBC driver available) within ADO.NET. However, the code is
  • 8. generally the same for both. With ADO, you can issue commands through the Command, the Connection, or the Recordset object. In ADO.NET, only the Commandobjects (SqlCommand or OleDbCommand) run commands. To run a command, follow these steps: 1. Follow these steps to create a new console application in Visual Basic .NET: a. Start Visual Studio .NET. b. On the File menu, point to New, and then click Project. c. In the New Project dialog box, click Visual Basic Projects under Project Types, and then click Console Application underTemplates. 2. Make sure that your project contains a reference to the System.Data namespace, and add a reference if it does not. 3. Use the Imports statement on the System and System.Data namespaces so that you do not have to qualify declarations in those namespaces later in your code. You can also include System.Data.SqlClient or System.Data.OleDb, depending on which one you are using. 4. 5. Imports System 6. Imports System.Data 7. Imports System.Data.SqlClient 8. Before you can create a connection to a database, you must have a connection string. Connection strings contain all of the information that you need to establish a database connection, including the server name, the database name, the user ID, and the password. For example, the following connection string points to a local computer that is running SQL Server with a strong password for the <username> account: For OleDb connections:
  • 9. 9. 10. Provider=SQLOLEDB.1;User ID=<username>;Password=<strong password>;Initial Catalog=pub s;Data Source=(local) For SqlClient connections: User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Data Source=(local ) NOTE: If you need more assistance determining the connection string for your database, search for "ConnectionString" in the Microsoft Developer Network (MSDN) Library at the following Microsoft Web site: http://msdn.microsoft.com/en-us/search/default.aspx 11. Visual Studio creates a module and an empty Main() procedure. Declare a string variable, and store the appropriate connection string for your database in this procedure: 12. 13. Sub Main() 14. Dim sConnectionString As String _ 15. = "User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Data So urce=(local)"
  • 10. 16. End Sub 17. Using this connection string, create a new OleDbConnection or SqlConnection object, and call its Open method to establish a connection to your database: 18. 19. Dim objConn As New SqlConnection(sConnectionString) 20. objConn.Open() 21. Create a SqlCommand or OleDbCommand object, and pass in the command that you want to run and the connection object that you created in the previous step. The following sample code passes in the INSERT statement: 22. 23. Dim sSQL As String = "INSERT INTO Employee " & _ 24. "(emp_id, fname, minit, lname, job_id, job_lvl, pub_id, hire_date)" & _ 25. "VALUES ('MSD12923F', 'Duncan', 'W', 'Mackenzie', " & _ 26. "10, 82,'0877','2001-01-01')" 27. Dim objCmd As New SqlCommand(sSQL, objConn)
  • 11. 28. After you create the SqlCommand or the OleDbCommand object, you can call the ExecuteNonQuery method to run the command that it represents. ExecuteNonQuery is designed for commands that do not return any results (such as the DELETE, the UPDATE, and the INSERT statements). If the Execute statement runs without throwing an exception (see the following code), the command has been executed successfully against the database. 29. 30. objCmd.ExecuteNonQuery() 31. Save your project. On the Debug menu, click Start to run your command against the database. How to use parameters When you run commands against a database (such as the UPDATE, the INSERT, and the DELETE statements or calls to stored procedures), these commands are frequently parameterized. This allows the command to be created one time but executed multiple times with different values that are inserted instead of parameters. Consider the corresponding DELETE statement to the INSERT statement that is used in the previous section: Dim sSQL As String = "DELETE FROM Employee WHERE emp_id = @emp_id"
  • 12. The parameter name ("@emp_id") in this DELETE statement represents a parameter than you can replace with different values each time you run the command. To use parameters with your command, follow these steps: 1. Create your OleDbConnection or SqlConnection object, as you did in the "How to Run a Command" section. 2. Replace the values with placeholders (for example, "@emp_id" or "@fname") so that your command text uses parameters. See the DELETE statement before these steps for an example. 3. Create your OleDbCommand or SqlCommand object, and pass in the connection object that you created in the first step and the command text that contains the parameter placeholders. 4. For each parameter, add a parameter object to the command object's parameters collection. For each parameter, you must specify a name and data type. 5. 6. objCmd.Parameters.Add("@emp_id", SqlDbType.Char, 9) 7. Stored procedures can have parameters that return values and output parameters. You must also set a value for each input parameter before you can run the query: 8. 9. objCmd.Parameters.Item("@emp_id").Value = "MSD12923F"
  • 13. 10. Run the query as follows: 11. 12. Try 13. objCmd.ExecuteNonQuery() 14. Console.WriteLine("Record Deleted") 15. Catch e As Exception 16. Console.WriteLine(e.ToString) 17. End Try 18. Console.WriteLine("Record Deleted") 19. Console.Read() Complete code listing Imports System Imports System.Data Imports System.Data.SqlClient Module Module1
  • 14. Sub Main() AddRecord() RemoveRecord() Pause() End Sub Sub Pause() Console.WriteLine("Press Enter To Continue...") Console.ReadLine() End Sub Sub AddRecord() Dim sConnectionString As String _ = "User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Dat a Source=(local)" Dim objConn As New SqlConnection(sConnectionString) objConn.Open() Dim sSQL As String = "INSERT INTO Employee " & _ "(emp_id, fname, minit, lname, job_id, job_lvl, pub_id, hire_date)" & _ "VALUES ('MSD12923F', 'Duncan', 'W', 'Mackenzie', " & _ "10, 82,'0877','2001-01-01')" Dim objCmd As New SqlCommand(sSQL, objConn) Try objCmd.ExecuteNonQuery() Catch e As Exception
  • 15. Console.WriteLine(e.Message) End Try Console.WriteLine("Record Added") End Sub Sub RemoveRecord() Dim sConnectionString As String _ = "User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Dat a Source=(local)" Dim objConn As New SqlConnection(sConnectionString) objConn.Open() Dim sSQL As String = "DELETE FROM Employee WHERE emp_id = @emp_id" Dim objCmd As New SqlCommand(sSQL, objConn) objCmd.Parameters.Add("@emp_id", SqlDbType.Char, 9) objCmd.Parameters.Item("@emp_id").Value = "MSD12923F" Try objCmd.ExecuteNonQuery() Console.WriteLine("Record Deleted") Catch e As Exception Console.WriteLine(e.ToString) End Try Console.WriteLine("Record Deleted") Console.ReadLine() End Sub
  • 16. End Module ADO.NET for the ADO Programmer Doug Rothaus Mike Pizzo Microsoft Corporation December 2001 Summary: This article presents an overview of the data access architecture available through ADO.NET, and answers the questions mostly commonly asked by developers familiar with ADO. (11 printed pages) Contents Introduction Overview The Design of ADO ADO.NET: Explicit and Factored Data Types Summary FAQ What happened to the Recordset? What happened to cursors? How do I populate a DataSet with data from my database if it is disconnected from the data source? How do I resolve changes to the DataSet back to the database? How do I use ADO.NET with XML, similar to adPersistXml? How do I use my existing COM components, which use ADO for data retrieval and updates, in the .NET Framework? Introduction In the .NET Framework, Microsoft introduces ADO.NET, an evolution of the data access architecture provided by the Microsoft® ActiveX® Data Objects (ADO) programming model. ADO.NET does not replace ADO for the COM programmer; rather, it provides the .NET programmer with access to relational data sources, XML, and application data. ADO.NET supports a variety of development needs, including the creation of database clients and middle-tier business objects used by applications, tools, languages, and Internet browsers.
  • 17. Built with the ADO programmer in mind, ADO.NET contains many similarities to ADO, and also introduces several new concepts in its design. This article addresses the most common questions the ADO programmer encounters when first examining ADO.NET. Overview From its inception, ADO has provided an efficient, robust interface for COM programmers to work with data. ADO is widely used as an interface to a variety of different stores because it can be called from any automation language including Microsoft Visual Basic® 6.0, Microsoft Visual C++®, and a variety of scripting interfaces. ADO.NET is an evolution of ADO that provides better platform interoperability and scalable data access. Creating a new set of data access APIs in ADO.NET offered the following advantages over directly porting ADO to the .NET Framework. Improved integration with XML: Subsequent to the design of ADO, XML began to play an increasingly significant role in the design of applications. ADO.NET was designed from the ground up to integrate with XML, and leverages XML in a fundamental way. In addition to persisting and loading both data and its relational structure as XML, ADO.NET relies on XML for remoting data between tiers or clients. The generic XML representation that ADO.NET uses provides a convenient method for transmitting data across any network, including those with restrictive security perimeters. ADO.NET also uses XML tools to perform validation, hierarchical queries, and data transformations on relational data. Integration with the .NET Framework: ADO constructs, such as the Recordset, do not employ familiar programming constructs but instead are modeled to be database-oriented. For example, cursors, which are used to navigate and retrieve data, function differently than other data constructs such as arrays and collections. In ADO.NET, however, in-memory data can be exposed through common .NET Framework structures, including arrays and collections, providing you with common access methods when working with relational data. Improved support for the disconnected business model: ADO provides limited support for disconnected access using the Recordset. ADO.NET introduces a new object, the DataSet, which serves as a common, in-memory representation of relational data. The DataSet is, by design, disconnected at all times. Because it holds no persistent connection to outside resources, it is ideal for packaging, exchanging, caching, persisting, and loading data. Explicit control of data access behaviors: The design of ADO includes implicit behaviors that may not always be required in an application and that may therefore limit performance. ADO.NET provides well- defined, factored components with predictable behavior, performance, and semantics that enable you to address common scenarios in a highly optimized manner. Improved design-time support: ADO derives information about data implicitly at run time, based on metadata that is often expensive to obtain. ADO.NET, on the other hand, leverages known metadata at design time in order to provide better run-time performance and more consistent run-time behavior. The Design of ADO To better understand the model and design of ADO.NET, it is helpful to review some of the core aspects of ADO. ADO uses a single object, the Recordset, as a common representation for working with all types of data. The Recordset is used for working with a forward-only stream of results from a database, for scrolling through data held on a server, or for scrolling through a set of cached results. Changes made to data may be applied immediately to the database, or applied as a batch using optimistic search and update operations. You specify the desired functionality when you create the Recordset, and the behavior of the resulting Recordset can vary greatly depending on the properties you request.
  • 18. Because ADO uses a single object that can behave in many different ways, it enables you to keep the object model of your applications very simple. However, it is difficult to write common, predictable, and optimized code because the behavior, performance, and semantics exhibited by that single object can vary greatly depending on how the object is generated and what data it is accessing. This is particularly true for generic components (such as a grid control) that attempt to consume data not generated by the component and for which the component has no ability to specify required behavior or functionality. ADO.NET: Explicit and Factored In designing ADO.NET, consideration was given to the tasks that developers commonly face when accessing and working with data. Rather than using a single object to perform a number of tasks, ADO.NET factors specific functionality into explicit objects that are optimized to enable developers to accomplish each task. The functionality that the ADO Recordset provides has been factored into the following explicit objects in ADO.NET: theDataReader, which provides fast, forward-only, read-only access to query results; the DataSet, which provides an in-memory relational representation of data; and the DataAdapter, which provides a bridge between the DataSet and the data source. The ADO.NET Command object also includes explicit functionality such as the ExecuteNonQuery method for commands that do not return rows, and the ExecuteScalar method for queries that return a single value rather than a row set. To better understand how the design of ADO.NET is made up of objects that are optimized to perform explicit behavior, consider the following tasks that are common when working with data. Forward-Only Read-Only Data Streams Applications, particularly middle-tier applications, often process a series of results programmatically, requiring no user interaction and no updating of or scrolling back through the results as they are read. In ADO, this type of data retrieval is performed using a Recordset with a forward-only cursor and a read-only lock. In ADO.NET, however, the DataReaderobject optimizes this type of data retrieval by providing a non-buffered, forward-only, read-only stream that provides the most efficient mechanism for retrieving results from the database. Much of this efficiency is gained as a result of theDataReader having been designed solely for this purpose, without having to support scenarios where data is updated at the data source or cached locally as with the ADO Recordset. Returning a Single Value Often the only data to be retrieved from a database is a single value (for example, an account balance). In ADO, you perform this type of data retrieval by creating a Recordset object, reading through the results, retrieving the single value, and then closing the Recordset. In ADO.NET, however, the Command object supports this function through theExecuteScalar method, which returns the single value from the database without having to introduce an additional object to hold the results. Disconnected Access to Data A frequent case for exposing data is a representation in which a user can navigate the data in an ad-hoc manner without holding locks or tying up resources on the server. Some examples of this scenario are binding data to a control or combining data from multiple data sources and/or XML. The ADO Recordset provides some support for these scenarios, using a client-side cursor location. However, in ADO.NET the DataSet is explicitly designed for such tasks. The DataSet provides a common, completely disconnected data representation that can hold results from a variety of different sources. Because the DataSet is completely independent of the data source, it provides the same performance and semantics regardless of whether the data is loaded from a database, loaded from XML, or is generated by the application. A single DataSet may contain tables populated from several different databases and other non-database sources; to the consumer of the DataSet it all looks and behaves exactly the same. Within the DataSet you can define relations to navigate from a table populated from one database (for example, "Customers"), to a related table populated from an entirely
  • 19. different database (for example, "Orders"), and from there to a third table (for example, "OrderDetails") containing values loaded from XML. The relational capabilities of the DataSet provide an advantage over the Recordset, which is limited to exposing the results from multiple tables either as a single joined result, or by returning multiple distinct result sets, requiring the developer to handle and relate the results manually. Though the Recordset has the ability to return and navigate hierarchical results (using the MSDataShape provider), the DataSet provides much greater flexibility when dealing with related result sets. The DataSet also provides the ability to transmit results to and from a remote client or server in an open XML format, with the schema defined using the XML Schema definition language (XSD). Retrieving and Updating Data from a Data Source Based on customer feedback and common use cases it is clear that in most application development scenarios (with the exception of ad-hoc tools and generic data components) the developer knows certain things about the data at design time that technologies like ADO attempt to derive at run time. For example, in most middle-tier applications the developer knows, at the time of application development, the type of database to be accessed, what queries will be executed, and how the results will be returned. ADO.NET gives you the ability to apply this knowledge at design time in order to provide better run-time performance and predictability. As an example, when using batch updating with ADO Recordset objects, you must submit changes to the database by executing appropriate INSERT, UPDATE, and DELETE statements for each row that has changed. ADO generates these statements implicitly, at run time, based on metadata that is often expensive to obtain. ADO.NET, however, enables you to explicitly specify INSERT, UPDATE, and DELETE commands, as well as custom business logic such as a stored procedure, that will be used to resolve changes in a DataSet back to the data source using the DataAdapter. This model provides you with greater control over how application data is returned and updated, and removes the expense of gathering the metadata at run time. The DataAdapter provides the bridge between the DataSet and the data source. A DataAdapter is used to populate aDataSet with results from a database, and to read changes out of a DataSet and resolve those changes back to the database. Using a separate object, the DataAdapter, to communicate with the database allows the DataSet to remain completely generic with respect to the data it contains, and gives you more control over when and how commands are executed and changes are sent to the database. ADO performs much of this behavior implicitly, however the explicit design of ADO.NET enables you to fine-tune your interaction with a data source for best performance and scalability. The implicit update behavior of ADO is also available in ADO.NET using a CommandBuilder object that, based on a single table SELECT, automatically generates the INSERT, UPDATE, and DELETE commands used for queries by theDataAdapter. However, the compromise for this convenience is slower performance and less control over how changes are propagated to the data source because, as with ADO, the commands are generated from metadata collected at run time. Data Types In ADO, all results are returned in a standard OLE Automation Variant type. This can hinder performance because, in addition to conversion overhead, variants are allocated using task-allocated system memory, which causes contention across the system. When retrieving results from a DataReader in ADO.NET, however, you can retrieve columns in their native data type, as a common Object class, without going through expensive conversions. Data values can either be exposed as .NET Framework types, or can be placed in a proprietary structure in the .NET Framework to preserve the fidelity of the native type. An example of this is the SQL Server .NET Data Provider, which can be used to expose Microsoft® SQL Server™ data as .NET Framework types, or as proprietary types defined by the classes in theSystem.Data.SqlTypes namespace.
  • 20. Summary ADO.NET is designed to build on the strength of the ADO programming model, while providing an evolution of data access technology to meet the changing needs of the developer. It is designed to leverage your existing knowledge of ADO, while giving you much finer control over the components, resources, and behavior of your applications when accessing and working with data. Related Topics in the .NET Framework SDK  Accessing Data with ADO.NET Describes ADO.NET architecture and how to use the ADO.NET classes to manage application data and interact with data sources including Microsoft SQL Server, OLE DB, and XML.  Overview of ADO.NET Provides an introduction to the design and components of ADO.NET.  Using .NET Data Providers to Access Data Describes the components of a .NET data provider and how to use them to access relational data sources.  Creating and Using DataSets Describes the DataSet and how to use it to manage relational data in your application.  XML and the DataSet Describes how the DataSet interacts with XML as a data source, including loading and persisting the contents of a DataSet as XML and synchronizing a DataSet with an XmlDataDocument. FAQ This section answers the questions most commonly asked by developers familiar with ADO as they begin to familiarize themselves with ADO.NET. What happened to the Recordset? The ADO Recordset bundles functionality together into one object and handles much behavior implicitly. ADO.NET, on the other hand, has been designed to factor behavior into separate components and to enable you to explicitly control behavior. The following table describes the individual ADO.NET objects that provide the functionality of the ADO Recordset. ADO.NET object Description
  • 21. DataReader Providesaforward-only,read-onlystreamof datafroma data source. The DataReader is similar to a Recordset with CursorType = adOpenForwardOnly and LockType = adLockReadOnly. DataSet Providesin-memoryaccesstorelationaldata. The DataSet is independent of any specific data source and therefore can be populated from multiple and differing data sources including relational databases and XML, or can be populated with data local to the application. Data is stored in a collection of one or more tables, and can be accessed non- sequentially and without limits to availability, unlike ADO in which data must be accessed a single row at a time. A DataSet can contain relationships between tables, similar to the ADO Recordset in which a single result set is created from a JOIN. A DataSet can also contain unique, primary key, and foreign key constraints on its tables. The DataSet is similar to a Recordset with CursorLocation = adUseClient,CursorType = adOpenStatic, and LockType = adLockOptimistic. However, the DataSet has extended capabilities over the Recordset for managing application data. DataAdapter PopulatesaDataSet withdata froma relational database andresolves changesinthe DataSet back to the data source. The DataAdapter enables you to explicitly specify behavior that the Recordset performs implicitly. Related Topics in the .NET Framework SDK  Retrieving Data Using the DataReader Describes the DataReader and how to use it to return results from a data source.  Creating and Using DataSets Describes the DataSet and how to use it to manage relational data in your application.  Populating a DataSet from a DataAdapter Describes how to fill the contents of a DataSet from a relational data source using a DataAdapter.  Updating the Database with a DataAdapter and the DataSet
  • 22. Describes how to resolve changes to data in a DataSet back to a data source using a DataAdapter.  Using .NET Data Providers to Access Data Describes the components of a .NET data provider and how to use them to access relational data sources. What happened to cursors? In ADO it is possible, within a common Recordset object, to request multiple and differing cursor types (dynamic, keyset, static, and forward-only) with different properties that define how the cursor behaves, for example whether the cursor is updateable or is read-only, or whether it is implemented on the client or on the server. In ADO.NET, however, different classes are exposed that give you greater control over each type of interaction. The DataReader provides an extremely fast, forward-only, read-only cursor on the server side that enables you to retrieve a stream of results from a database. The DataSet provides a completely disconnected "client" cursor, through which you can scroll and update, that is equivalent to the static cursor in ADO. These objects, along with the DataAdapter that enables you to move data between the DataSet and a database, provide you with optimal access methods for the most common types of data interactions. Note that ADO.NET version 1.0 does not expose a scrollable, updateable server-side cursor. Applications that require scrolling and positioned updates on the client side generally involve user interaction. Because server-side cursors require state to be held on the server, your application will not be robust or scalable if it must hold those valuable resources while users interact with the data on the client side. Most applications that currently use scrollable server-side cursors on the client could be much more efficiently written according to one of the following designs:  Use stored procedures to handle custom logic, to run on the server instead of the client.  Use a forward-only, read-only cursor to return data from the server, and execute commands to process any updates.  Populate a DataSet with results, modify the data locally, and then propagate those changes back to the server. Related Topics in the .NET Framework SDK  Using .NET Data Providers to Access Data Describes the components of a .NET data provider and how to use them to access relational data sources.  Optimistic Concurrency Describes the optimistic concurrency model and how to use ADO.NET to handle optimistic concurrency violations.  Paging Through a Query Result Provides an example of returning the results of a query as smaller sections, or "pages", of data.
  • 23. How do I populate a DataSet with data from my database if it is disconnected from the data source? How do I resolve changes to the DataSet back to the database? The DataAdapter provides the bridge between the DataSet and the data source. You control the behavior for populating the DataSet and resolving inserts, updates, and deletes in the DataSet back to the data source by defining explicit commands that the DataAdapter will use. The DataAdapter command properties are the SelectCommand, InsertCommand, UpdateCommand, andDeleteCommand. Each command corresponds directly to a SELECT, INSERT, UPDATE, and DELETE action at the data source. Additionally, these actions can be optimized as a stored procedure call. Once the DataAdapter commands have been defined, you can pass a DataSet to the Fill method of a DataAdapter to fill a DataSet with the results returned by the SelectCommand, or pass a DataSet to the Update method of a DataAdapter to propagate changes in the DataSetback to the data source. The InsertCommand will process rows that have been added to the DataSet. TheUpdateCommand will process existing rows that have been modified in the DataSet. The DeleteCommand will process existing rows that have been deleted from the DataSet. Related Topics in the .NET Framework SDK  Updating the Database with a DataAdapter and the DataSet Describes how to resolve changes to data in a DataSet back to a data source using a DataAdapter.  Populating a DataSet from a DataAdapter Describes how to fill the contents of a DataSet from a relational data source using a DataAdapter.  Using .NET Data Providers to Access Data Describes the components of a .NET data provider and how to use them to access relational data sources. How do I use ADO.NET with XML, similar to adPersistXml? The DataSet provides extensive support for using XML to load and persist the schema and data within a DataSet. You can load the contents of the DataSet from any XML format, and write the contents of a DataSet to an XML format that is much simpler and more generic than that of an ADO Recordset saved as XML. The schema, or relational structure, of aDataSet can easily be persisted as, or created from, a simple XML Schema definition language (XSD) schema. If an XML document has no XML Schema supplied, and no schema is defined within the DataSet, the DataSet can infer the schema from the XML elements in the XML document. Additionally, the DataSet gives you control over how rows and columns are written to and read from an XML document. Columns can be mapped as attributes, elements, or simple content, or can be hidden (not written out). Related rows can be nested within their parent element, or treated as sibling elements. The DataSet can also be synchronized with an XmlDataDocument to provide simultaneous relational and hierarchical views of a single set of data. By synchronizing a DataSet with an XmlDataDocument, you also gain access to other XML functionality for the data in your DataSet such as the ability to perform
  • 24. XML Path Language (XPath) queries over the data or to apply an Extensible Stylesheet Language Transformation (XSLT transformation) to the data. The SQL Server .NET Data Provider also provides the capability, using the SqlCommand, to return the results of FOR XML queries against Microsoft SQL Server 2000 or later directly as an XmlReader. In addition to the XML capabilities provided with ADO.NET, SQLXML 2.0 (XML for SQL Server 2000) contains SQLXML Managed Classes that enable you to access the XML functionality of Microsoft SQL Server 2000 and later from the .NET Framework. For example, these classes allow you to execute XML templates, perform XPath queries over data at the server, or perform updates to data using Updategrams or Diffgrams. Related Topics in the .NET Framework SDK  Obtaining Data as XML from SQL Server Describes how to return the results of a FOR XML query in Microsoft SQL Server 2000 or later as an XmlReaderusing the SQL Server .NET Data Provider.  XML and the DataSet Describes how the DataSet interacts with XML as a data source, including loading and persisting the contents of a DataSet as XML and synchronizing a DataSet with an XmlDataDocument.  SQLXML 2.0 (XML for SQL Server 2000) Provides the release of XML for Microsoft SQL Server 2000 (SQLXML 2.0), which includes SQLXML Managed Classes for use in the .NET Framework. How do I use my existing COM components, which use ADO for data retrieval and updates, in the .NET Framework? COM components that return or consume ADO objects are available in the .NET Framework using COM interop services. Additionally, the OLE DB .NET Data Provider includes overloads to the OleDbDataAdapter.Fill method which take as input an ADO Recordset or Record object returned by existing COM components, and populate a DataSet with the data contained in the ADO object. Updates to the data in the DataSet can be propagated back to the data source using aDataAdapter. You can also use an Extensible Stylesheet Language Transformation (XSLT transformation) to transform between the XML format of the ADO Recordset and the XML format of the ADO.NET DataSet. Related Topics in the .NET Framework SDK  Accessing an ADO Recordset or Record from ADO.NET Describes how to use the OleDbDataAdapter to fill the contents of a DataSet or DataTable from an ADO Recordset or Record object.  Exposing COM Components to the .NET Framework Describes how to access COM components from within the .NET Framework.