0% found this document useful (0 votes)
36 views42 pages

Introduction To

Introduction to ADO.NET

Uploaded by

R K Aggarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
36 views42 pages

Introduction To

Introduction to ADO.NET

Uploaded by

R K Aggarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 42
EG Introduction to ADO.NET = What we cover... » Differences Between ADO and ADO.NET = Benefits of ADO.NET « ADO.NET Core Concepts and Architecture = The ADO.NET Object Model = The DataSet and Data Views = Managed Providers mg ADO.NET and the .NET Framework Microsoft .NET Framework Web Services User Interface Data and XML EE ae ADO.NET Overview —_ What Is ADO.NET? = ADO .NET is a collection of classes, interfaces, structures, and enumerated types that manage data access from relational data stores within the .NET Framework » These collections are organized into namespaces: = System.Data, System.Data.OleDb, System.Data.SqlClient, etc. = ADO .NET is an evolution from ADO. = Does not share the same object model, but shares many of the same paradigms and functionality! ADO.NET Overview Managed Providers = Merges ADO and OLEDB into one layer = Each provider contains a set of classes that implement common interfaces = Initial managed provider implementations: » ADO Managed Provider: provides access to any OLE DB data source » SQL Server Managed Provider: provides optimal performance when using SQL Server » Exchange Managed Provider: retrieve and update data in Microsoft Exchange ADO.NET Overview Managed Providers SQL Server Database pao Database mm 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 » Data sharing via COM marshalling = Problems marshalling through firewalls (DCOM, binary) mm ADO vs. ADO.NET cont. = ADO.NET Designed for disconnected access Can model data logically! 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” mg Benefits of ADO.NET = Interoperability through use of XML » Open standard for data that describes itself « Human readable and decipherable text « Used internally but accessible externally = Can use XML to read and write and move data = Scalability through the disconnected DataSet » Connections are not maintained for long periods » Database locking does not occur = Locking support with ServiceComponents = Optimistic locking otherwise = Works the way the Web works: “Hit and Run!” = Maintainability s = Separation of data logic and user interface mal 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.SqiClient = System.Data.Sql Types amg ADO.NET-related Namespaces System.Data motel] el-1<) -SqlClient Resaued OleDb Class Browser for System.data and System.data.sqlclient 10 mm ADO.Net - Introducing the objects = Connection = used to talk to DB;properties include dataSource, username and password » SQLConnection and OleDbConnection = Command » An SQL statement or Stored Procedure » SQLCommand and OleDbComand = DataReader- read only, forward only view of data CF ADO Recordset = DataSet - main object for DB access = DataView - filtered view of DataSet « =DataAdapter - Initialises DataSet tables EE Introducing the Objects cont. | System.Data _ | = Contains the “main” classes of ADO.NET DataSet DataTable DataRow DataColumn DataRelation DataViewManager| = 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 System.Data Namespace Contains the basis and bulk of 12 ADO.NET mag DB Connection Example-1 <%@ Page Language="vb" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqIClient” %> DB Connection Example-2 A crit language="VB" runat="Server'> Sub Page_Load(Src As Object, E As EventArgs) Dim ds As DataSet Dim conn As SQLConnection Dim cmdAuthors As SQLDataAdapter Dim dv As DataView ‘create a connection to the Pubs database’ conn = New SQLConnection _ ("server=localhost;uid=sa;pwd=super ;database=pubs") ‘create a dataset with information from the authors table’ cmdAuthors = New SQLDataAdapter _ ("select * from Authors", conn) ds = new DataSet() emdAuthors.Fill(ds, "Authors') ‘Authors is the DataTable name in ds was DB Connection Example-3 ‘pind the first datagrid to the DefaultView of the dataset’ dv = ds. Tables("Authors").DefaultView dgAuthors.DataSource = dv dgAuthors.DataBind() ‘create a new DataView that is authors from California’ ‘and bind the second datagrid to it’ dv = New DataView(ds. Tables("Authors")) dv.RowFilter = "state = 'CA™ dgCAAuthors.DataSource = dv dgCAAuthors.DataBind() End Sub mam DB Connection Example-4

All Authors

California Authors

mam DB Connection Example-5 = Demo the previous code. = http://interdev.csse.monash.edu.au/cse2030/jason1/grid.aspx = NOTE: » Namespaces included in page directives » Objects used: = SqlConnection ; SqiDataAdapter; Dataset; DataView; » Web Form Controls used: = = Grid.DataBind() moves data from memory (dataview) to web page = DataGrid does not have to be bound to dataset; can be bound to a hashtable say http://jasonc.csse.monash.edu.au/chapter7/datagridsimple.aspx = For source see 17 http:/www.csse.monash.edu.au/courseware/cse2030/2002/datagridsimple.txt = ADO.NET Classes DataSet DataSet DataTable Datacolumn DataRow DataRelation mi Putting the Objects Together... DataSet Relations DataRelation DataRelation DataTable DataTable Poesy DataTable DataView DataViewManager mm 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 20 ma Properties & Methods of Interest = Collections are used to add & remove tables & relations = Properties of Interest: « Tables: Returns the collection of DataTable objects = Relations: Returns the collection of DataRelations = Namespace: Gets or sets the namespace of the DataSet = Using Properties Samples: = myDataSet.Tables.Add( myTable ); = myDataTablecollection = myDataSet.Tables 21 mm The DataTable = May be mapped to a physical table in the data source = Can be related to one another through DataRelations = Optimistic concurrency or locking - model = Properties of Interest: » Columns: Returns ColumnsCollection of DataColumns » Rows: Returns DataRow objects as a RowsCollection » ParentRelations: Returns the RelationsCollection = Constraints: Returns the table’s ConstraintsCollection = DataSet: Returns the DataSet of the DataTable = PrimaryKey: Gets the DataColumns that make up the table’s primary key 2 mm System.Data—DataSet and DataTable = Create a DataTable and add it to a DataSet DataSet ds = new DataSet(); // Create DataTable object: “Customers”. DataTable dt= new DataTable( “Customers” ); // Create and add columns to the table // 1. Explicitly create and Add a DataColumn Datacolumn dc; dc = new DataColumn( “CustID”, Type.GetTypeC("System. Int16")); dt.columns.Add( dc ); / 2. Implicitly Create and Add columns (DataColumn) . dt.Columns.Add( “First_Name”, Type.GetType("System String”)); dt.columns.Add( “Last_Name”, Type.GetType("System String”)); ‘/ Add the DataTable object to the DataSet ds.Tables.Add( dt ); 23 DataSet, DataRelation, Data...Views DataSet DataView DataViewManager DataViewSettings L DataViewSetting Relations DataRelation PE Vc lee lela) DataViewSetting ma Viewing Data - The DataView = Create multiple views on DataTable objects = Bindable to user interface controls = Properties of Interest: » Table: Retrieves or sets the associated DataTable «= Sort: Gets or sets the table’s sort columns and sort order » RowFilter: Gets or sets the expression used to filter rows «= RowStateFilter: Gets or sets the row state filter = None, Unchanged, New, Deleted, ModifiedCurrent, and others 25 El Creating a DataView by Example // Code for myTable “Customers” with “Name” column not shown Dataview viewl = new DataView( myTable ); Dataview view2 = new DataView( myTable ); // Creates Ascending view of Customers by “Name” viewl.sort = “Name ASC”; // Set the view to show only modified (original) rows view2.RowStateFilter= DataViewRowState.Modifiedoriginal; // Bind to UI element(s)... DataGrid myGrid = new DataGrid(Q); myGrid.SetDataBinding( viewl, “Customer”); Vane 26 mm Viewing More Data - DataViewManager = Similar to a DataView but DataSet oriented = Used to create multiple views on a DataSet » Ability to automatically set filters on the tables = Properties of Interest: = DataViewSettings: Gets the DataView for on each DataTable » DataSet: Gets or sets the DataSet to be viewed = CreateDataView method = Creates a DataView on a DataTable a mi DataViewManager By Example // Create the DataViewManager & views... DataViewManager dvMgr = new DataViewManager( myDS ); dvMgr.CreateDataView( ds.Tables[“Orders"] ); dvmgr .DataviewSettings[“Orders"].Sort = “CustID ASC"; dvmgr .CreateDataview( ds.Tables[“Customers"] ); dvmgr .DataviewSettings[“Customers"].Sort = “Name DESC"; // Bind to a UI elements/controls... dataGrid1.DataSource = viewMgr; dataGridl.DataMember = "Tablel"; dataGrid2.DataSource = viewMgr; dataGrid2.DataMember = "Table2"; // Update the control with the data... dataGrid1.update() ; dataGrid2.update() ; 28 mm The (ADO).NET Data Providers = Acollection of classes for accessing data sources: » Microsoft SQL Server™ 2000, SQL Server 7, and MSDE » Any OLE Database (OLE DB) providers = Including: Oracle, JET, and SQL OLE DB Providers » Establish connection between DataSets and data stores = Two .NET data providers: » ADO: via the System.Data.OleDb namespace = SQL Server: via the System.Data.SqIClient namespace = System.Data.OleDb is the .NET data provider 29 Mg .NET Data Providers Hierarchy -Common Contains classes shared by both System.Data -SqlClient melee mi OleDbConnection and SqiConnection = Represent a unique session with a data source = Create, open, close a connection to a data source = Functionality and methods to perform transactions = OleDbConnection example: String conStr="Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=NWIND_RW.MDB"; OleDbConnection aConn = new OleDbConnection(constr) ; aconn.Open(); // Execute Queries using OleDbDataAdapter Class aconn.Close(); 31 Relational Databases Stored Procedure Example CREATE PROCEDURE CustOrderHist @CustomerID nchar(5) AS SELECT ProductName, Total=SUM(Quantity) FROM Products P, [Order Details] OD, Orders 0, Customers C WHERE C.CustomerID = @CustomerID AND C.CustomerID = O.CustomerID AND 0.OrderID = OD.OrderID AND OD.ProductID = P.ProductID GROUP BY ProductName 2 mm ADO.NET - Data Binding = Key component of Web Forms framework = Flexible and easy to use » Bind a control’s property to information in any type of data store » Provides control over how data moves back and forth « Simple controls for displaying a single value eg below using binding tags <%# %> = Complex controls for displaying a data structure eg datagrid 38 = ADO.NET Classes System.Data.Sq1Client Namespace 34 Managed provider native to SQL Server Built on TDS (Tabular Data Stream) for high performance in SQL Server Sq1Connection, Sq1Command and Sq|DataReader classes Classes for « Error handling = Connection pooling (implicitly enabled by default ) System.Data.Sql]Types provides classes for native SQL Server data types = ADO.NET Classes DataSet Example string sConnString = “Persist Security Info=False;” + “User ID=sa;Initial Catalog=Northwind;” + “Data Source=MYSERVER”; Sqlconnection conn = new SqlConnection(sConnstring) ; conn.Open() ; string sQueryString = “SELECT CompanyName FROM Customers”; SqlDataadapter myDsAdapter = new SqIDataAdapter(); DataSet myDataSet = new DataSet(); myDSAdapter.SelectCommand = new SqiCommand(sQueryString, conn); myDSAdapter.Fil] (myDataSet) ; conn.Close(); 35 Stored Procedure Example <%@ Page Language="vb" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.Sq|Client" %>