adonet training
DESCRIPTION
dssTRANSCRIPT
Technology Solutions Lab Confidential and Proprietary
Data Management
ADO.NET
Data Management
ADO.NET
Technology Solutions Lab 2Confidential and Proprietary
AgendaAgenda
•Introduction to ADO.NET
•Programming with ADO.NET
•DAAB
•Session Summary
Technology Solutions Lab 3Confidential and Proprietary
Introduction to ADO.NETIntroduction to ADO.NET
•Natural Evolution of ADO
•Interoperability – Based on standards like XML, XSD
•Scalability– Targets distributed, disconnected web scenarios
•High-performance design– Optimized providers and Objects
What is ADO.NET?What is ADO.NET?
Technology Solutions Lab 4Confidential and Proprietary
Introduction to ADO.NETIntroduction to ADO.NET
DataReaderDataReader
DataAdapterDataAdapter
DataSetDataSet
CommandCommand CommandCommand
ConnectionConnectionConnectionConnection
RecordSetRecordSet
ADO ADO ADO .NET ADO .NET
Technology Solutions Lab 5Confidential and Proprietary
Introduction to ADO.NETIntroduction to ADO.NETADO.NET and the .NET FrameworkADO.NET and the .NET Framework
Microsoft .NET Framework
Common Language Runtime
Base Classes
Web Services User Interface
Data and XML
ADO.NET XML ... ...
Technology Solutions Lab 6Confidential and Proprietary
Introduction to ADO.NETIntroduction to ADO.NET
Managed ProviderManaged Provider
DataReaderDataReader
CommandCommandConnectionConnection
SyncSync
Controls,Controls,Designers,Designers,
Code-gen, etcCode-gen, etc
DataSetDataSet
XmlReaderXmlReader
XmlText-XmlText-ReaderReader
XmlNode-XmlNode-ReaderReader
XSL/T, X-Path,XSL/T, X-Path,Validation, etcValidation, etc
XmlData-XmlData-DocumentDocument
DataAdapterDataAdapter
Managed Data OverviewManaged Data Overview
Technology Solutions Lab 7Confidential and Proprietary
Introduction to ADO.NETIntroduction to ADO.NET
Business TierBusiness Tier Data TierData Tier
Windows Forms
Web Forms
Business to Business
Data Object (Class)
DataSet
DataSetDataSet
InternetInternetIntranetIntranet
Data AdapterData Adapter
Data AdapterData Adapter
(BizTalk, for example)
XML
ADO.NET in action…ADO.NET in action…
Technology Solutions Lab 8Confidential and Proprietary
Introduction to ADO.NETIntroduction to ADO.NET
•System.Data.SqlClient. Contains the SQL Server .NET Data Provider types.
•System.Data.OracleClient. Contains the Oracle .NET Data Provider types
•System.Data.OleDb. Contains the OLE DB .NET Data Provider types.
•System.Data.Odbc. Contains the ODBC .NET Data Provider types.
•System.Data. Contains provider-independent types such as the DataSet and DataTable.
Namespace OrganizationNamespace Organization
Technology Solutions Lab 9Confidential and Proprietary
Introduction to ADO.NETIntroduction to ADO.NETData access stackData access stack
Technology Solutions Lab 10Confidential and Proprietary
AgendaAgenda
•Introduction to ADO.NET
•Programming with ADO.NET
•DAAB
•Session Summary
Technology Solutions Lab 11Confidential and Proprietary
Programming with ADO.NETProgramming with ADO.NETManaged Data ProvidersManaged Data Providers
•ADO.NET relies on the services of .NET data providers
–SQL Server .NET Data Provider
–Oracle .NET Data Provider
–OLE DB .NET Data Provider
–ODBC .NET Data Provider
–Managed provider for retrieving XML from SQL Server 2000 (refer:http://msdn.microsoft.com/library/default.asp?url=/nhp/default.asp?contentid=28001300)
•NET Data Provider Object Model–Connection
–Command
–DataReader :Like a recordset but Forward only and read only
–DataAdapter: Transfers data between Database and Dataset
Technology Solutions Lab 12Confidential and Proprietary
Programming with ADO.NETProgramming with ADO.NET
•Represents A Connection To The Data Source
•On A Connection, You Can…– Represent a unique session with a data source– Create, open, close a connection to a data source
ChangeDatabase, Connection pooling
– Create a Command object associated with the connection
CreateCommand
– Begin, commit, and abort transactions
•Equivalent To The ADODB.Connection Object
ConnectionConnection
Technology Solutions Lab 13Confidential and Proprietary
Programming with ADO.NETProgramming with ADO.NET
•Example://Specify the System.Data.SQL Namespace//using System.Data.SqlClient
//Create an instance of an SqlConnection objectSqlConnection cnn = new SqlConnection();//Set the connection stringcnn.ConnectionString = "Data Source=.;Initial
Catalog=Northwind;Integrated Security=SSPI";
//Open the Connectioncnn.Open();
ConnectionConnection
Technology Solutions Lab 14Confidential and Proprietary
•Connection Pooling Example:IDbConnection conn = new SqlConnection();conn.ConnectionString = “Integrated Security=SSPI; Initial
Catalog=Northwind”conn.Open(); // Pool A is created;
IDbConnection conn = new SqlConnection();conn.ConnectionString = “Integrated Security=SSPI; Initial
Catalog=pubs”conn.Open(); // Pool B is created because connection
string is different
IDbConnection conn = new SqlConnection();conn.ConnectionString = “Integrated Security=SSPI; Initial
Catalog=Northwind”conn.Open(); // Uses Pool A
Programming with ADO.NETProgramming with ADO.NETConnectionConnection
Technology Solutions Lab 15Confidential and Proprietary
•Represents a query to execute on the data source– May be a SQL statement or stored procedure
•Properties of Interest:– Connection: Get or set the data source connection– CommandText: Get or set the query (text) command
A SQL statement or the name of the stored procedure
– CommandType: Get/set how the command is interpreted
Text, StoredProcedure, or TableDirectNote: TableDirect is only supported by the .NET
Framework Data Provider for OLE DB.
– CommandTimeout: The seconds until connection timeout
Programming with ADO.NETProgramming with ADO.NETCommandCommand
Technology Solutions Lab 16Confidential and Proprietary
•Forward-only data access•“Lightweight” programming model
– Less overhead than using DataAdapter
•Instantiated & returned by Command.ExecuteReader
•Ties up the Command until it is finished reading
•Allows Strongly-Typed Access– Example: GetDateTime, GetDouble, GetGuid,
GetInt32•Properties of Interest:
– FieldCount: Returns the number of fields in the result set– RecordsAffected: Number of affected records
Is not set until all rows are read and you close the DataReader
The number of rows changed, inserted, or deleted; 0 if no rows were affected or the statement failed; and -1 for SELECT statements.
IsClosed and RecordsAffected are the only properties that you can call after the DataReader is closed.
Programming with ADO.NETProgramming with ADO.NETDataReaderDataReader
Technology Solutions Lab 17Confidential and Proprietary
•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
Programming with ADO.NETProgramming with ADO.NETDataReaderDataReader
Technology Solutions Lab 18Confidential and Proprietary
// Code for creating the OleDbConnection “adoConn” not shownString 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 donereader.Close();adoConn.Close();
Programming with ADO.NETProgramming with ADO.NETDataReader: ExampleDataReader: Example
Technology Solutions Lab 19Confidential and Proprietary
•Bridge between the DataSet and the data store•Means to modify the DataSet and data source
Programming with ADO.NETProgramming with ADO.NETDataAdapterDataAdapter
DataAdapterDataAdapter
SelectCommandSelectCommand
InsertCommandInsertCommand
UpdateCommandUpdateCommand
DeleteCommandDeleteCommand
TableMappingsTableMappings
Data storeData store
DataSetDataSet
Technology Solutions Lab 20Confidential and Proprietary
•RowUpdated, RowUpdating event handlers ptovides facility to access the row before updating and after updating
•MissingMappingAction– Determines the action to take when incoming
data does not have a matching table or columnPassthrough, Ignore, Error
•MissingSchemaAction – Determines the action to take when existing
DataSet schema does not match incoming data.Add, AddWithKey, Ignore, Error
Programming with ADO.NETProgramming with ADO.NETDataAdapterDataAdapter
Technology Solutions Lab 21Confidential and Proprietary
•In memory store for client data
•Relational view of data– Tables, Columns, Rows– Constraints, Relations
•Persist Data And Schema As XML
•Explicit Disconnected Model– Disconnected, remotable object
Programming with ADO.NETProgramming with ADO.NETDataSetDataSet
RelationRelation
RowRow
ConstraintConstraint
ColumnColumn
TableTable
ColumnsColumns
ConstraintsConstraints
RowsRows
DataSetDataSet
TablesTables
RelationsRelations
Technology Solutions Lab 22Confidential and Proprietary
DataSet Tables
DataTable
Relations
DataRelation
DataRelationDataTable
DataTable
DataView
DataViewManager
DataRow(s)
DataColumn
Constraint(s)
Programming with ADO.NETProgramming with ADO.NETDataSetDataSet
Technology Solutions Lab 23Confidential and Proprietary
Extracts tablesExtracts tablesWith ManagedWith Managed
ProviderProvider
Resolves changesResolves changeswith Managedwith ManagedProviderProvider
Makes changesMakes changesto datato data
Sets upSets uprelationshipsrelationships
OriginalDataStore
DataSet
Table1
Table2
DataSet
Table1
Table2
DataSet
Table1
Table2
Programming with ADO.NETProgramming with ADO.NETDataSet Life cycleDataSet Life cycle
ConnectedConnectedOperationsOperations
DisconnectedDisconnectedOperationsOperations
Technology Solutions Lab 24Confidential and Proprietary
•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
Programming with ADO.NETProgramming with ADO.NETDataSet DataSet DataTable DataTable
Technology Solutions Lab 25Confidential and Proprietary
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 DataColumnDataColumn dc; dc = new DataColumn( “CustID”,
Type.GetType("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 DataSetds.Tables.Add( dt );
Programming with ADO.NETProgramming with ADO.NETDataSet DataSet DataTable Example DataTable Example
•Create a DataTable and add it to a DataSet
Technology Solutions Lab 26Confidential and Proprietary
SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");
SqlDataAdapter custDA = new SqlDataAdapter("SELECT CustomerID, CompanyName FROM Customers ORDER BY CustomerID", nwindConn);
// The Update command checks for optimistic concurrency violations in the WHERE clause. custDA.UpdateCommand = new SqlCommand("UPDATE Customers (CustomerID, CompanyName)
VALUES(@CustomerID, @CompanyName) " + "WHERE CustomerID = @oldCustomerID AND CompanyName = @oldCompanyName",
nwindConn); custDA.UpdateCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID"); custDA.UpdateCommand.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 30, "CompanyName"); // Pass the original values to the WHERE clause parameters. SqlParameter myParm; myParm = custDA.UpdateCommand.Parameters.Add("@oldCustomerID", SqlDbType.NChar, 5, "CustomerID"); myParm.SourceVersion = DataRowVersion.Original; myParm = custDA.UpdateCommand.Parameters.Add("@oldCompanyName", SqlDbType.NVarChar, 30,
"CompanyName"); myParm.SourceVersion = DataRowVersion.Original; // Add the RowUpdated event handler. custDA.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated); DataSet custDS = new DataSet(); custDA.Fill(custDS, "Customers"); // Modify the DataSet contents. custDA.Update(custDS, "Customers"); foreach (DataRow myRow in custDS.Tables["Customers"].Rows) { if (myRow.HasErrors) Console.WriteLine(myRow[0] + "\n" + myRow.RowError); }protected static void OnRowUpdated(object sender, SqlRowUpdatedEventArgs args){ if (args.RecordsAffected == 0) { args.Row.RowError = "Optimistic Concurrency Violation Encountered"; args.Status = UpdateStatus.SkipCurrentRow; }}
Programming with ADO.NETProgramming with ADO.NETDataSet DataSet Optimistic concurrency Example Optimistic concurrency Example
Technology Solutions Lab 27Confidential and Proprietary
•Used to create logical relations between your data– Create relations between two (2) DataTable
objects– Requires a DataColumn object from each DataTable– The DataType of both DataColumns must be the
sameCannot relate a Int32 DataColumn and a String
DataColumn– The relation is named (by you!)
DataRelation dr=new DataRelation( “myRelation”,...)
•RelationsCollection used to hold/group them– Accessed through the DataSet’s Relations property
Programming with ADO.NETProgramming with ADO.NETDataSet DataSet DataTable Relations:DataRelation object DataTable Relations:DataRelation object
Technology Solutions Lab 28Confidential and Proprietary
// Building on the DataTable example earlier... // Get the DataTable DataColumns we want to relate...
DataColumn parentCol, childCol;parentCol=
DataSet.Tables["Customers"].Columns["CustID"];childCol = DataSet.Tables["Orders“].Columns["CustID"];
// Create DataRelation with the name “CustomerOrders”...
DataRelation dr = new DataRelation("CustomersOrders", parentCol, childCol);
// Add the relation to the DataSet... ds.Relations.Add( dr );
Programming with ADO.NETProgramming with ADO.NETDataSet DataSet DataTable Relations:DataRelation object DataTable Relations:DataRelation object
•Example
Technology Solutions Lab 29Confidential and Proprietary
•DataSet can read/write XML for its data and/or schema– You can create or modify data in a DataSet using XML– You can create or modify the DataSets schema using XML
•XML-related DataSet methods for reading:– ReadXml: Reads an XML schema and data into the DataSet– ReadXmlSchema: Reads an XML schema into the DataSet
•And for writing: – WriteXml, WriteXmlSchema– GetXml, GetXmlSchema
•Namespace property: – The Namespace property is used when reading and writing
an XML document into the DataSet
•Full support for DiffGrams– A DiffGram is an XML format that is used to identify
current and original versions of data elements
Programming with ADO.NETProgramming with ADO.NETDataSet and XMLDataSet and XML
Technology Solutions Lab 30Confidential and Proprietary
// Code for creating the DataSet mds and loading the // DataSet from a data source not shown.
String oFile = “C:\\My_ADO.NET\\myXmlOutput.xsd”;String iFile = “C:\\My_ADO.NET\\myXmlInput.xml”; // Write the DataSet’s XMLSchema to an XML Documentmds.WriteXmlSchema( oFile );
// Read/Upload XML Data into the DataSetmds.ReadXml( iFile);
// modify the data // ...
// Write the existing Data to an XML Documentmds.WriteXml( "C:\\My_ADO.NET\\myXmlData.xml",
XmlWriteMode.DiffGram);
Programming with ADO.NETProgramming with ADO.NETDataSet and XML: ExampleDataSet and XML: Example
Technology Solutions Lab 31Confidential and Proprietary
•Exposes relational view over structured XML
•Allows strong typing, control binding, relational access of XML data
•Allows XML tools (schema validation, XSL/T, XPath queries) against relational data
•Preserves full fidelity of XML Document
Programming with ADO.NETProgramming with ADO.NETDataSet and XmlDataDocumentDataSet and XmlDataDocument
Technology Solutions Lab 32Confidential and Proprietary
Programming with ADO.NETProgramming with ADO.NETDataSet and XmlDataDocumentDataSet and XmlDataDocument
Technology Solutions Lab 33Confidential and Proprietary
// Associate an XmlDataDocument with the DataSetXmlDataDocument xmlDocument = new XmlDataDocument(pubs);
// Get an XmlNavigator for the XmlDataDocumentDataDocumentNavigator xmlNavigator = new
DataDocumentNavigator(xmlDocument);
// Get all the authors from CAxmlNavigator.Select("//Authors[state='CA']/au_lname");
// Write out all of the authors' last nameswhile(xmlNavigator.MoveToNextSelected()){
Console.WriteLine("Name = " + xmlNavigator.InnerText);}
//As usual, you can navigate the data using the DataSet
DataRow row;foreach(row in xmlDocument .DataSet.Tables[0].Rows) {
Console.WriteLine(row[1]) ; //prints au_lname}
Programming with ADO.NETProgramming with ADO.NETDataSet and XmlDataDocument : ExampleDataSet and XmlDataDocument : Example
Technology Solutions Lab 34Confidential and Proprietary
•Populate DataSet with XML DocumentDataSet RegionDS = new DataSet();
RegionDS.ReadXmlSchema( "Region_More.XSD" ); XmlDataDocument DataDoc = new XmlDataDocument( RegionDS ); DataDoc.Load("Region_More.XML" );
//Now RegionDS contains data loaded from XML file
Programming with ADO.NETProgramming with ADO.NETDataSet and XmlDataDocument : ExampleDataSet and XmlDataDocument : Example
Technology Solutions Lab 35Confidential and Proprietary
DataViewManagerDataViewSettings
DataSet Tables
DataTable
Relations
DataRelation
DataRelationDataTable
DataTable
DataView
DataViewSetting
DataViewSetting
DataRow(s)
DataColumn
Constraint(s)
Programming with ADO.NETProgramming with ADO.NETDataViewsDataViews
Technology Solutions Lab 36Confidential and Proprietary
•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 filterNone, Unchanged, New, Deleted, ModifiedCurrent, and
others
Programming with ADO.NETProgramming with ADO.NETDataViews: Viewing DataDataViews: Viewing Data
Technology Solutions Lab 37Confidential and Proprietary
// Code for myTable “Customers” with “Name” column not shown
DataView view1 = new DataView( myTable );DataView view2 = new DataView( myTable );
// Creates Ascending view of Customers by “Name”view1.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();myGrid.SetDataBinding( view1, “Customer”);
//...
Programming with ADO.NETProgramming with ADO.NETDataViews: Viewing Data: ExampleDataViews: Viewing Data: Example
Technology Solutions Lab 38Confidential and Proprietary
•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
Programming with ADO.NETProgramming with ADO.NETDataViews: Viewing More Data : DataViewManagerDataViews: Viewing More Data : DataViewManager
Technology Solutions Lab 39Confidential and Proprietary
// 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;dataGrid1.DataMember = "Table1";
dataGrid2.DataSource = viewMgr;dataGrid2.DataMember = "Table2";
// Update the control with the data...dataGrid1.Update();dataGrid2.Update();
Programming with ADO.NETProgramming with ADO.NETDataViews: DataViewManager : ExampleDataViews: DataViewManager : Example
Technology Solutions Lab 40Confidential and Proprietary
1. adpter.Fill(ds,startrecord, maxrecords,sourceTableName)
2. switch (direction) //Next, Previous { case "Next": selCmd.CommandText = "SELECT TOP " + pageSize + " CustomerID, CompanyName FROM
Customers " + "WHERE CustomerID > @CustomerId ORDER BY CustomerID"; selCmd.Parameters.Add("@CustomerId", SqlDbType.VarChar, 5).Value =
lastVisibleCustomer; break; case "Previous": selCmd.CommandText = "SELECT TOP " + pageSize + " CustomerID, CompanyName FROM
Customers " + "WHERE CustomerID < @CustomerId ORDER BY CustomerID DESC"; selCmd.Parameters.Add("@CustomerId", SqlDbType.VarChar, 5).Value =
firstVisibleCustomer; break; default: selCmd.CommandText = "SELECT TOP " + pageSize + " CustomerID, CompanyName FROM
Customers ORDER BY CustomerID"; // Determine total pages. SqlCommand totCMD = new SqlCommand("SELECT Count(*) FROM Customers", nwindConn); nwindConn.Open(); int totalRecords = (int)totCMD.ExecuteScalar(); nwindConn.Close(); totalPages = (int)Math.Ceiling((double)totalRecords / pageSize);
break; }
Programming with ADO.NETProgramming with ADO.NETPaging: ExamplesPaging: Examples
Technology Solutions Lab 41Confidential and Proprietary
AgendaAgenda
•Introduction to ADO.NET
•Programming with ADO.NET
•DAAB
•Session Summary
Technology Solutions Lab 43Confidential and Proprietary
•SqlHelper class – provides a set of static methods that you can use to
execute a variety of different command types against a SQL Server database.
•SqlHelperParameterCache class – provides command parameter caching functionality
used to improve performance. This is used internally by a number of the Execute methods (specifically, the overloads that are designed to execute only stored procedures). It can also be used directly by the data access client to cache specific parameter sets for specific commands.
– Uses sp_procedure_params_rowset procedure
•URL: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/daab-rm.asp
DAABDAAB
Technology Solutions Lab 44Confidential and Proprietary
AgendaAgenda
•Introduction to ADO.NET
•Programming with ADO.NET
•DAAB
•Session Summary
Technology Solutions Lab 45Confidential and Proprietary
User / Browser
IIS
DataAccess
Database
Base C
omponents
BusinessRules
EA
F
Web
ASP.NET
DAL1
DAAB
ADO.NET
Session SummarySession SummaryBflex applications Architecture OverviewBflex applications Architecture Overview