View
215
Download
0
Category
Tags:
Preview:
Citation preview
1
17. Data Access
ADO.Net ArchitectureNew Features of ADO.NETVisual Studio Visual Studio Wizards and
Designers Demonstration: Creating Data ComponentsLab 17: Accessing Data Using ADO.NET
Code Samples
2
ADO.NET Architecture
What Is ADO.NET?What Is a Connected Environment?What Is a Disconnected Environment?What Is the ADO.NET Object Model?What Is the DataSet Class?What Is the .NET Data Provider?
3
What Is ADO.NET?ADO.NET is a data access technology. It provides: A set of classes, interfaces, structures, and
enumerations that manage data access from within the .NET Framework
An evolutionary, more flexible successor to ADO A system designed for disconnected environments A programming model with advanced XML support
4
What Is a Connected Environment?
A connected environment is one in which users are constantly connected to a data source
Advantages: Environment is easier to secure Concurrency is more easily controlled Data is more likely to be current than in other scenarios
Disadvantages: Must have a constant network connection Scalability
5
What Is a Disconnected Environment? In a disconnected environment, a subset of data from
a central data store can be copied and modified independently, and the changes merged back into the central data store
Advantages You can work at any time that is convenient for you, and can
connect to a data source at any time to process requests Other users can use the connection A disconnected environment improves the scalability and
performance of applications Disadvantages
Data is not always up to date Change conflicts can occur and must be resolved
6
What Is the ADO.NET Object Model?DataSetDataSet
DatabaseDatabaseDatabaseDatabase
.NET Data Provider.NET Data Provider
ConnectionConnection
TransactionTransaction
CommandCommand
ParametersParameters
DataReaderDataReader
DataAdapterDataAdapter
SelectCommandSelectCommand
InsertCommandInsertCommand
UpdateCommandUpdateCommand
DeleteCommandDeleteCommand
DataTableCollectionDataTableCollection
DataTableDataTable
DataRowCollectionDataRowCollection
DataColumnCollectionDataColumnCollection
ConstraintCollectionConstraintCollection
DataRelationCollectionDataRelationCollection
XMLXMLXMLXML
7
What Is the .NET Data Provider?
Manages the connection to a database
Manages the connection to a database
Executes a query command on the database
Executes a query command on the database
Exchanges data between the data set and the database
Exchanges data between the data set and the database
Provides efficient access to astream of read-only data
Provides efficient access to astream of read-only data
DatabaseDatabaseDatabaseDatabase
ConnectionConnection
CommandCommand
DataReaderDataReader
DataAdapterDataAdapter
8
Creating an Application That Uses ADO.NET to Access DataHow to Specify the Database ConnectionHow to Specify the Database CommandHow to Create the DataAdapter ObjectHow to Create a DataSet ObjectHow to Bind a DataSet to a DataGridHow to Use the Data Wizards in Visual Studio .NET
9
How to Specify the Database Connection Use the Connection object to:
Choose the connection type Specify the data source Open the connection to the data source
Use the connection string to specify all of the options for your connection to the database, including the account name, database server, and database name
string connectionStr = @"Data Source=localhost; Integrated Security=SSPI; Initial Catalog=northwind";
string connectionStr = @"Data Source=localhost; Integrated Security=SSPI; Initial Catalog=northwind";
10
How to Specify the Database Command
Create a string containing SQL statements Remember that Verbatim strings can make this much
easier!
Examples of SQL statements: SELECT * FROM Customers
SELECT CustomerName FROM Customers
SELECT * FROM Customers WHERE Country = 'Mexico'
string commandStr=@"SELECT CustomerName, CompanyName FROM Customers";
string commandStr=@"SELECT CustomerName, CompanyName FROM Customers";
11
How to Create the DataAdapter Object
Data sourceDataAdapterDataTable
DataTable
DataSet
DataAdapter
FillFill
UpdateUpdate
UpdateUpdate
FillFill
12
What Is the DataSet Class?
DataSetDataSet
ConstraintsConstraints
TableTable
ColumnColumn
ConstraintConstraint
RowsRows
RowRow
RelationsRelations
RelationRelation
ObjectObject CollectionCollection
TablesTables
ColumnsColumns
DataSets consist of one or more tables and relationsLoaded from one or more
data adaptersCreated as you workLoaded from XMLLoaded from other
DataSetsTables contain columns,
constraints, and rowsAll are collections!
13
How to Bind a DataSet to a DataGrid
DataGrid dataGrid1 = new DataGrid();sqlDataAdapter1.Fill(dataSet1, "Customers");sqlDataAdapter2.Fill(dataSet1, "Orders");dataGrid1.DataSource = dataSet1;
DataGrid dataGrid1 = new DataGrid();sqlDataAdapter1.Fill(dataSet1, "Customers");sqlDataAdapter2.Fill(dataSet1, "Orders");dataGrid1.DataSource = dataSet1;
To bind programmatically
14
Changing Database Records
How to Access Data in a DataSet ObjectHow to Update a Database in ADO.NETHow to Create a Database RecordHow to Update a Database RecordHow to Delete a Database Record
15
DataRowobjects
How to Access Data in a DataSet Object
DataColumnobjects
DataTableobjects
DataColumnobjects
16
How to Update a Database in ADO.NET
DataSet
Client
DataAdapter
DatabaseDatabaseDatabaseDatabase
Server
DataData
FillFill
UpdateUpdate
DeleteCommandDeleteCommand
UpdateCommandUpdateCommand
InsertCommandInsertCommand
DataData
DataTable
17
How to (Manually) Create a Database Record
Create a new row that matches the table schema
Add the new row to the dataset
Update the database
Create a new row that matches the table schema
Add the new row to the dataset
Update the database
DataRow myRow = dataTable.NewRow();DataRow myRow = dataTable.NewRow();
sqlDataAdapter1.Update( dataSet );sqlDataAdapter1.Update( dataSet );
dataTable.Rows.Add( myRow );dataTable.Rows.Add( myRow );
18
How to (Manually) Delete a Database Record
Delete the row from the dataset
Update the database
Accept the changes to the dataset
dataTable.Rows[0].Delete();dataTable.Rows[0].Delete();
dataSet.AcceptChanges();dataSet.AcceptChanges();
dataAdapter.Update(dataSet);dataAdapter.Update(dataSet);
19
Data Reader
Data Readers manage the stream of results from a SELECT statement or Stored Procedure
Data Readers are read only Data Readers only move forwards through the data –
they cannot go backwards No other database operation can be performed while
a data reader is open
20
Using a DataReader with a SELECT Statement
string queryString = "SELECT FirstName, LastName FROM dbo.Employees";
//Create the command objects SqlCommand com = new SqlCommand(queryString, conn);
//Call the command's ExecuteReader method SqlDataReader dr = com.ExecuteReader();
//Loop through the datareader to output the employee names while (dr.Read()) { listBox1.Items.Add(dr.GetString(0) + " " +
dr.GetString(1)); }
21
Using a DataReader to call a Stored Procedure
//Create the command object and set its properties SqlCommand com = new SqlCommand(); com.Connection = conn; com.CommandText = "CustOrderHist"; com.CommandType = CommandType.StoredProcedure;
//Create the parameter object and add it to the command's collection SqlParameter param =
new SqlParameter("@CustomerID", SqlDbType.NVarChar, 5); param.Value = txtID.Text; com.Parameters.Add(param);
22
Creating a Two Tier ApplicationCreate the data tier
Create a new class library projectCreate a class to represent a business entity, say
customersAdd methods that access the database, using ADO.NetAdd properties that expose attributes, say name, phone …
Create the presentation tierCreate a new Windows Application projectAdd a reference to the above data projectCreate an object from classUse the object’s properties to populate controls on a formUse the object’s methods to access the database
23
New Features of ADO.NET 2.0
Multiple active result setsOne connection can host more than one result setReduces number of connections on a database
Asynchronous operationsBegin a data access operation, continue with other tasks,
and then later end the original operation
Batch updatesUpdate multiple rows in one batchUse the UpdateBatchSize property of the DataAdapter
24
Visual Studio Wizards and Designers
Data Source Configuration WizardTableAdapter Configuration WizardTableAdapter Query Configuration WizardPreview Data Dialog Box
25
Lab 17: Accessing Data Using ADO.NET
Exercise 1: Retrieving Data into a Data Set Exercise 2: Updating the Database from a Data Set Exercise 3: Retrieving Data with a Data Reader Exercise 4: Calling a Stored Procedure
Recommended