Beruflich Dokumente
Kultur Dokumente
NET:
Most applications handle data, whether in the form of a database, text file,
spreadsheet, whatever the majority of modern day programs need access to an
information store. ADO.NET technology fulfills these needs for .NET programs.
ADO.NET is the new database technology of the .NET platform, and it builds on ADO
(ActiveX Data Objects). ADO.NET is an object-oriented set of libraries that allows you
to interact with data sources. Commonly, the data source is a database, but it could
also be a text file, an Excel spreadsheet, or an XML file.
ADO.NET brings along with it four, much-publicized advantages:
Interoperability - All data in ADO.NET is transported in XML format, meaning it's
simply a structured text document that can be read by anyone on any platform.
Scalability - The client/server model is out. ADO.NET promotes the use of
disconnected datasets, with automatic connection pooling bundled as part of the
package.
Productivity - You can't just pick it up and run, but ADO.NET can certainly improve
your overall development time. For example, "Typed DataSets" help you work quicker
and produce more bug-free code.
Performance - Because ADO.NET is mainly about disconnected datasets, the
database server is no longer a bottleneck and hence applications should incur a
performance boost.
For the past several years, ADO.NET has been one of the primary technologies for
connecting to a database with .NET applications. It offers a high level of abstraction,
allowing a more object oriented approach to working with data than was possible
with earlier data access technologies. With ADO.NET, a program can view, insert,
update, and delete database records. It supports both a connected and disconnected
model.
First, lets take a look at ADO.NET architecture.
Page 1
www.magix.in
DataSet:
Once we've created a connection to the database and retrieved data from it, we can
manipulate that data within our program using a DataSet object. The DataSet
contains a collection of DataTable objects, and any relations between them. A
DataTable - as its name suggests - stores data in a tabular format; that is, in columns
and rows. It can be considered as a local copy of the relevant portions of the
database. Because the DataSet doesn't form part of the data provider (there's only
one type of DataSet object, regardless of whether the data comes from SQL Server,
or an OLE DB data source), the DataSet doesn't maintain a connection to the data
source. This means that when we manipulate data in a DataSet, we're just working
with a copy of the data in memory on the local machine. This eases the strain on the
database server and on the network, because we only connect to the data source
when we first get the data, and when we've finished editing it and want to upload our
changes back to the database.
Data Provider
The Data Provider is responsible for providing and maintaining the connection to the
database. A DataProvider is a set of related components that work together to
provide data in an efficient and performance driven manner.
The data provider consists of a number of data source-specific components that
allow us to connect to and communicate with individual data sources. Each data
provider resides in its own namespace within the System.Data namespace. At the
time of writing, there are five data providers available:
The data provider for SQL Server- This resides in the System.Data.SqlClient
namespace, and is used to connect to SQL Server 7.0 or greater and MSDE
databases (MSDE is a cut-down version of SQL Server). The SQL Server provider
is shipped as part of the .NET Framework. If you need to connect to a SQL
Server 6.5 or earlier database, you will need to use the OLE DB provider.
The data provider for OLE DB- This is used to connect to data sources through
OLE DB and resides in the System.Data.OleDb namespace. Like the SQL
Server provider, it also ships with the .NET Framework. The OLE DB provider
cannot be used to connect to databases through ODBC drivers.
Page 2
www.magix.in
The data provider for ODBC- The ODBC provider can be used to connect to
databases which have ODBC drivers. The ODBC data provider namespace is
Microsoft.Data.Odbc.
The data provider for ORACLE- This resides in the System.Data.Oracle
namespace, and is used to connect to Oracle database server.
The BORLAND data provider- This resides in the System.Data.Bdp
namespace, and is used to Generic access to many databases such as
Interbase, SQL Server, IBM DB2, and Oracle.
Each DataProvider consists of the following component classes:
Component
Description
Name
Connection
Used to connect to a database or other data source.
Command
Used to retrieve, edit, delete, or insert data in the
database.
DataReader
Provides a stream of data from the data source. This
data can only be read (it can't be modified), and we can
only move forwards through the data.
DataAdapter
populates a disconnected DataSet with data and
performs update.
www.magix.in
Page 4
www.magix.in
1.
2.
3.
4.
5.
6.
ADO.NET makes it easy to manage data in a disconnected mode; it isnt the recommended
solution for all problems. Youll have to make a design decision, based on your application
requirements, as to whether working with disconnected mode is more of a benefit than
connected mode. If you need data persisted to the database immediately, use connected
mode. However, if you have isolated data that no one else will change or the data rarely
changes, maybe your analysis will reveal that disconnected mode has a benefit in your
situation.
www.magix.in
Page 6
www.magix.in
Page 7
www.magix.in
Page 8
www.magix.in
Each data provider has a Connection class. Below Table shows the name of various
connection classes for data providers.
Table: Data provider connection classes
Data Provider
1.
2.
3.
4.
OldDB
Sql
ODBC
Oracle
1.
2.
3.
4.
Connection Class
OleDbConnection
SqlConnection
OdbcConnection
OracleConnection
As from upper discussion, you probably know that for a connection we first need to
set a connection string. Many things can go into a connection stringdepending, of
course, upon the provider and configuration. Connection String is a normal String
representation which contains Database connection information to establish the
connection between Database and the Application. The Connection String includes
parameters such as the name of the driver, Server name and Database name, as
well as security information such as user name and password. Data providers use
a connection string containing a collection of parameters to establish the connection
with the database. Lets have some examples:
Microsoft SQL Server Connection String
connetionString ="Data Source = ServerName; Initial Catalog = Databasename; User
ID = UserName; Password=Password"
OLEDB Data Provider Connection String
connetionString = "Provider = Microsoft.Jet.OLEDB.4.0;
yourdatabasename.mdb;"
ODBC Connection String
connetionString = "Driver = {Microsoft Access
yourdatabasename.mdb;"
Driver
Data
Source
(*.mdb)};
DBQ
Note: You have to provide the necessary information to the Connection String attributes.
When you have a connection string, youre ready to connect to your data source. A
connection represents a live connection to the data source. Before seeing the code to
establish a database connection, you should be aware of the cost of connections. As
a general rule of thumb, database connections are expensive, and acquiring new
connections can be costly both in terms of time and resources.
To help alleviate this, many data providers support the notion of connection pooling.
When pooling is used, connections are placed in a pool when they are first created.
When a pooled connection is closed, it is returned to the pool instead of being
Page 9
www.magix.in
www.magix.in
Command objects commonly provide three methods that are used to execute commands
on the database:
ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE
or DELETE
ExecuteScalar:
Returns a single value from a database query (return first column of the
first row in the resultset.)
ExecuteReader:
Returns a result set by way of a DataReader object
Lets have a simple code snippet to show how this works:
The output of this code is all rows of column1 from table1.Don't forget to close both
Connection and DataReader at the end of your operations.
Page 11
www.magix.in
Page 12
www.magix.in
Dataadapters are used for two main purposes. They are listed below:
To fetch data from the database and display them in the datatables of dataset.
This is achieved using Fill method of dataadapter.
To fetch data from dataset and update them in necessary tables of database.
This is achieved using Update method of dataadapter.
There are four different types of Dataadapters. Their purpose and usage is mentioned
below:
OleDbDataAdapter: Dataadapters used to interact with databases through OLE
DB provider. It belongs to System.Data.OleDb namespace.
SqlDataAdapter: Dataadapters used to interact with SQL Server database with
version 7.0 or higher through Tabular data services. It belongs to
System.Data.SqlClient namespace.
OdbcDataAdapter: Dataadapters used to interact with databases exposed by
an ODBC provider. It belongs to System.Data.Odbc namespace.
OracleDataAdapter: Dataadapters used to interact with Oracle database. It
belongs to System.Data.OracleClient namespace.
Dataadapter has four different properties which controls database updates. The
properties are SelectCommand, UpdateCommand, InsertCommand and
DeleteCommand. These commands are used to read, update, add and delete
records from a database respectively.
//Create an instance of a OleDbDataAdapter
//by passing OleDbConnection object and select.. query
OleDbDataAdapter dAdapter = new OleDbDataAdapter ("select * from PersonTable", con );
www.magix.in
If we observe above code we will get a runtime error when this code gets
executed as the value assigned to the column (empno) does not take string
value.
Page 14
www.magix.in
If we see above code, a typed dataset is very much similar to a normal dataset.
But the only difference is that the schema is already present for the same.
Hence any mismatch in the column will generate compile time errors rather
than runtime error as in the case of normal dataset. Also accessing the column
value is much easier than the normal dataset as the column definition will be
available in the schema.
Note: We will soon learn how to create a typed dataset.
Page 15
www.magix.in
DataSets are memory structures that do not contain any data by default. DataSets
will have to be filled with data. This can be done in several ways.
1) By calling the Fill method of DataAdapter. For example:
//Create DataAdapter
SqlDataAdapter
daEmp
=
new
SqlDataAdapter("SELECT
empno,
empname,empaddress FROM EMPLOYEE",conn);
//Create a DataSet Object
DataSet dsEmp = new DataSet();
//Fill the DataSet
daEmp.Fill(dsEmp,"EMPLOYEE");
2) Manually populate the DataSets by creating DataRow objects and call the
AddNew method. For example:
DataSet dset;
DataTable dtbl;
DataRow drow;
//create a new row
drow=dtbl.NewRow();
//manipulate the newly added row using an index or the column name
drow["LastName"]="Altindag";
drow[1]="Altindag";
//After data is inserted into the new row, the Add method is used
//to add the row to the DataRowCollection
dtbl.Rows.Add(drow);
//You can also call the Add method to add a new row by passing in an
//array of values, typed as Object
dtbl.Rows.Add(new object[] {1, "Altindag"});
3) Read an XML Document or stream into the dataset.
4) Copy the contents of one DataSet with another.
5) Copy the contents of one DataTable into a DataSet
A DataSet can store not only the data but also information about the data such as
original, modified, inserted and deleted. Update of the underlying data-store is also
possible. This can be done by calling the Update method of the TableDataAdapter
or DataAdapter.
Page 16
www.magix.in
1.
2.
3.
4.
5.
Untyped DataSet
1. It is not as easy to use as strongly
typed dataset.
2. You will get type mismatch and other
errors at runtime.
3. You can't get an advantage of
intelliSense.
4. Performance is faster in case of
Untyped dataset.
5. Untyped datasets are easy to
administer.
Page 17
www.magix.in
6. Click the top label. Press F4 to display the Properties window. Change the Text property to
Title. Click the other label, and then change its Text property to YearReleased.
7. To add a new DataSet to the project, press CTRL+SHIFT+A, and then click DataSet in the list of
templates. Name the DataSet the following: dsProducts.xsd. Click Ok. Visual Studio will
recommend placing the DataSet file inside the App_Code folder, which you should allow it to
do for you. Note that the file is actually an XML Schema.
8. The dsProducts.xsd will open in design mode, and the TableAdapter Configuration Wizard
will launch. For now, just click Cancel, as we will add tables by dragging them from the Server
Explorer.
9. To create a typed DataSet, press CTRL+ALT+S to open the Server Explorer. We can start
designing the dataset. Now defining the dataset can be done in two ways,
A. Using the tool box
B. Using the server explorer
10. Here we will use the second method. Now the first thing we must do is to Add a new
Data Source to our project
c.
d.
e.
f.
g.
11.
Drag the DVDs tables to your DataSet Designer window. The window should now resemble the screen
shot below. What are we looking at? For each table we added, Visual Studio created a strongly typed
DataTable (the name is based on the original table) and a TableAdapter. The DataTable has each
column defined for us. The table adapter is the object we will use to fill the table. By default we have a
Fill() method that will find every row from that table.
Page 18
www.magix.in
12. By default it will have a TableAdapter (DVDsTableAdapter here) with Fill() and GetData()
methods that can be used to fill and fetch data from the database without implementing a
line of code.
13. To write code to display the typed DataSet, double-click directly on the Web Form (not on a
Web Control). The Web Form's codebehind appears, and the insertion point is inside the
Page_Load event.
14. In the Page_Load event procedure, create a Connection object by passing the connection
string to the default constructor of the SqlConnection class:
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Program
Files\Microsoft
Visual
Studio
8\Common7\IDE\ProjectTemplatesCache\CSharp\Starter
Kits\1033\MovieCollection.zip\DVDCollectionDatabase.mdf;Integrated Security=True;User Instance=True");
15. Create a SqlCommand object that is then passed to the SqlDataAdapter object. Pass an
improvised SQL statement and the new Connection object to the SqlCommand constructor.
The former sets the CommandText property of the new SqlCommand object. You can also
pass the name of a stored procedure.
SqlCommand cmd = new SqlCommand("select * from DVDs", con);
16. Create an instance of the SqlDataAdapter object, passing the new SqlCommand object
to the constructor:
SqlDataAdapter sda = new SqlDataAdapter(cmd);
17. Now you create the objects that are required to connect to the database and return data. The
following is the code for the typed DataSet. Note that an instance of the dsProducts class is
created: the class that maps to the dsProducts Schema and inherits from the DataSet class,
not the generic DataSet class itself.
sda.Fill(tds, DVDs);
19. To set the Text property of the text box controls to the strongly typed columns in the typed
DataSet's DataTable, use the following format:
tds.DataTableName[RowIndex].ColumnName
For this sample application, the RowIndex is hard-coded to 5:
TextBox1.Text = tds.DVDs[5].Title;
TextBox2.Text = tds.DVDs[5].YearReleased;
Because the Rows collection is zero-based, when the page loads, note that the text box
controls display the product and category names of the item in the sixth row of the GridView.
20. To display all of the results in the GridView1, set the DataSource property of the
GridView1 to the new typed DataSet, and call DataBind():
GridView1.DataSource = tds;
GridView1.DataBind( );
Page 19
www.magix.in
<!DOCTYPE
html
PUBLIC
"-//W3C//DTD
XHTML
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1.0
Transitional//EN"
www.magix.in
Now we know something about ADO.NET and how to use it. We will use this concept
with .NET controls to manipulate them. See ya in the next chapter.
Conclusion:
This chapter has touched a very big topic: ADO.NET database connectivity. The bad
news is that this topic alone is way too vast to be covered in a single chapter. The
good news is the material in this chapter will help point you in the right directions for
your own applications.
Page 21
www.magix.in