Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 26

Overview of ADO.NET with the .

NET Framework

ADO.NET

ADO.NET deals with accessing Databases. Its a new technology that runs within the .NET environment. It uses the concept of managed code. ADO.NET provides access to data sources such as Microsoft SQL Server, OLE DB and XML. Applications connect to these data sources to access, manipulate or update data.

Writing into the database 1. Prepare the connection string, say myConnStr, which would contain the relevant information about the data store. An example would be: String myConnStr; myConnStr= "User ID=sa; Initial Catalog=Northwind;" + "Data Source=mySqlServer;Password=;"; OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=D:\\MCA\pro.mdb"); Be sure to substitute your user id, Sql Server name and password appropriately.

2. Instantiate a Connection object, say myConn as SQLConnection myConn = new SQLConnection(myConnStr);. Prepare the SQL string that will be used to extract necessary data from the data store, for example: String mySql; // build the sql query string mySql = "Insert into Product values(12,"wheat",20)"; try{ str="Insert into pro2(firstname,lastname) values('kailash','kandpal')"; 4. Instantiate a Command object by passing the connection object and the SQL string as follows: SQLCommand myCmd = new SQLCommand(mySql, myConn); OleDbCommand cmd = new OleDbCommand(str,cn);

5. Open the Connection, as myConn.Open(); cmd.Connection.Open(); cmd.Connection.Open(); 6. The final step is to execute the command with: myCmd.ExecuteNonQuery() cmd.ExecuteNonQuery(); cmd.Connection.Close(); } catch (Exception e1) { } }

Selection Example
public void ConnectToAccess() { System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(); // TODO: Modify the connection string and include any // additional required properties for your database. conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data source= C:\Documents and Settings\username\" + @"My Documents\AccessFile.mdb"; try{ conn.Open();// Insert code to process data. }catch (Exception ex){ MessageBox.Show("Failed to connect to data source");}finally{conn.Close();} }

Managed Data Overview

ADO vs. ADO.NET


ADO
Designed for connected access Tied to the physical data model The RecordSet is the central data container RecordSet is one (1) table that contains all the data

Retrieving data from > 1 table or source requires a database JOIN Data is flattened : lose relationships; navigation is sequential
Data types are bound to COM/COM+ data types

ADO vs. ADO.NET


ADO.NET
Designed for disconnected access The DataSet replaces the RecordSet DataSet can contain multiple tables

Retrieving data from > 1 table or source does not require a JOIN Relationships are preserved: navigation is relational
Data types are only bound to XML schema No data type conversions required XML, like HTML, is plaintext: Firewall friendly

Core Concepts and Architecture


The ADO.NET Object Model Objects of System.Data .NET data providers ADO.NET namespace hierarchy Organizes the object model Includes: System.Data System.Data.OleDb System.Data.Common System.Data.SqlClient System.Data.SqlTypes

ADO.NET-related Namespaces
ADO.NET

System.Data

.SqlTypes

.SqlClient

.Common

.OleDb

Introducing the Objects


System.Data
DataSet DataTable DataRow DataColumn DataRelation DataViewManager

Contains the main classes of ADO.NET In-memory cache of data In-memory cache of a database table Used to manipulate a row in a DataTable Used to define the columns in a DataTable Used to relate 2 DataTables to each other
Used to create views on DataSets

Putting the Objects Together


DataSet
Tables
DataTable
DataRow(s)

DataView

Relations
DataRelation DataRelation

DataColumn Constraint(s)

DataViewManager

DataTable DataTable

DataSet
Common client data store
DataSet Tables Table Columns Column Constraints Constraint Rows Row Relations Relation

Relational View of Data


Tables, Columns, Rows, Constraints, Relations

Directly create metadata and insert data

Working Data - The DataSet


 

 

An in-memory cache of data from a data source Common way to represent and manipulate data  Universal data container  Not just for use with databases Logical or physical representation of data Designed to be disconnected from the data source  Connect, execute query, disconnect Can use XML  To read and write data  To read and write XMLSchema

Connected Data Access


Connected Data Access - Managed Providers
Connection, Transaction

Connecting to DataSource Starting/Ending Transactions


Command, Parameters

Database Updates, Selects, DDL


DataReader

(FO/RO) Server Cursor


DataAdapter

Pushing data into Dataset Reading changes out of DataSet

.Common
Contains classes shared by both

.NET Data Providers Hierarchy


System.Data
.SqlClient SqlCommand SqlConnection SqlDataReader SqlDataAdapter .OleDb OleDbCommand OleDbConnection OleDbDataReader OleDbDataAdapter

Data Adapter
Loads a table from a data store and writes changes back.
Exposes two important methods:
Fill(DataSet,DataTable) Update(DataSet,DataTable)

Provides mappings between tables & columns User provides insert/update/delete commands
Allows use of Stored Procedures CommandBuilder component available (not used much in ASP.NET)

Allows single DataSet to be populated from multiple different datasources

OleDbDataAdapter Class 1/2


Bridge between the DataSet and the data store Inherited from the DataAdapter class Means to modify the DataSet and data source

data store

DataAdapter

DataSet

Code: Retrieving Results


Create and open an OleDbConnection
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=D:\\MCA\std.mdb"; string query = "SELECT * FROM student"; dAdapter = new OleDbDataAdapter(query, connString); OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter); DataSet ds = new DataSet(); dAdapter.Fill(ds,"pro2"); foreach(DataRow row in ds.Tables["pro2"].Rows) MessageBox.Show(""+row[0]);

Code: Insert/Update/Delete

String str = ""; OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=D:\\MCA\pro.mdb"); try { str="Insert into pro2(firstname,lastname) values(name1',name2')"; OleDbCommand cmd = new OleDbCommand(str,cn); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } catch (Exception e1) { } }

OleDbDataReader

Forward-only data access Lightweight programming model Less overhead than using OleDbDataAdapter Instantiated & returned by OleDbCommand.ExecuteReader Ties up the OleDbCommand until it is finished reading

OleDbDataReader
Properties of Interest: FieldCount: Returns the number of fields in the result set RecordsAffected: Number of affected records Methods to retrieve data: By column type and/or index: GetValue; GetString; etc. Read(): Advances reader to next record NextResult(): Advanced to next result set in batch GetValues(): Gets the current row

OleDbDataReader Sample
// Code for creating the OleDbConnection adoConn not shown String myQuery = SELECT * FROM Customers; adoConn.Open(); OleDbCommand myCmd = new OleDbCommand( myQuery,adoConn ); // Declare the OleDbDataReader & // then instantiate it with ExecuteReader(...) ... OleDbDataReader reader = myCmd.ExecuteReader(); // Always call Read before accessing data. while( reader.Read() ) { Object [] cols = new Object[10] ; reader.GetValues( cols ); Console.WriteLine( cols[0].ToString() + " | " + cols[1] ); } // Always Close the reader and the connection when done reader.Close(); adoConn.Close();

Cleanup

Close your connection objects and return them to the connection pool. Dispose all objects. Don't wait on the finalizer.

Summary
ADO.NET is
Optimized for Data Access.

Managed Providers for connected access DataSet for disconnected, user interaction DataReader for connected RO use.
Open Architecture

No Black Boxes
Tightly Integrated with XML

DataSet reads/writes XML XmlDataDocument integrates relational and XML views

You might also like