Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID =...

31
5/29/2013 5/29/2013 5/29/2013 5/29/2013 1 Data Access This material is based on the original slides of Dr. Mark Sapossnek, Computer Science Department, Boston University, Mosh Teitelbaum, evoch, LLC, and Joe Hummel, Lake Forest College Outline Relational Databases ADO.NET Overview ADO.NET Classes

Transcript of Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID =...

Page 1: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

1111

Data Access

This material is based on the original slides of Dr. Mark Sapossnek, Computer Science Department, Boston University, Mosh Teitelbaum, evoch, LLC, and Joe Hummel, Lake Forest College

Outline

� Relational Databases

� ADO.NET Overview

� ADO.NET Classes

Page 2: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

2222

Databases Databases

� Virtually all interesting applications require a structured, persistent data store

� E-Commerce: placing an order, fulfilling an order

� HR: Personnel data

� Sales

� Database needs vary with the type of application

� Transaction Processing/OLTP

� Business Intelligence/Data Warehouse/OLAP

Relational DatabasesTables

� Table (relation, entity)� A collection of data about

a specific type of thing

� Organized in rows and columns

� Column (attribute, field)� Describes part of an entity (e.g. FirstName)

� Has a data type (e.g. integer, character, binary)

� Can be null

� Row (tuple, record)� A single instance of data in a table

� Each row is unique

AuthID FirstName LastName

1 Joe Smith

2 Diane Jones

Page 3: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

3333

Relational DatabasesRelating Data

� Tables can be related through primary/foreign key relationships (e.g., a book has an author)

� Primary key

� Guarantees the uniqueness of a row

� Can be composed of one or more columns

� Ensures entity integrity

� Foreign key

� Establishes logical relationship between tables

� One or more columns of a table that match the primary or alternate key of another table

� Referential integrity

Relational DatabasesRelating Data

Primary Key

Foreign Key

Books Table

Authors Table

PK/FK Relationship

AuthID FirstName LastName

1 Joe Smith

2 Diane Jones

BookID AuthID Title Type

1 2 My Life as a DBA Autobiography

2 1 Database Handbook Reference

Page 4: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

4444

Relational DatabasesNormalization/Denormalization

� Normalization

� The process of breaking large tables into multiple smaller tables

� Goal: minimize redundant data, maximize correctness

� Improves performance for updates

� Desirable in transaction-based applications

� Denormalization

� The process of combining smaller tables into fewer larger tables

� Goal: improve performance

� Introduces redundant data

� Improves performance for reads

� Desirable in data warehouse applications

Relational DatabasesJoins

� A join is a way of combining data in multiple tables, usually by resolving primary key/foreign key relationships

$25

$8

$5

$10

Cost

BleccoFoobar

Blecco

AcmeThingy

Widget

Acme

Vendor

Widget

Product

Product table

Blecco

Acme

Vendor

Adam P.

Linda A.

Contact

WA

MA

State

Vendor table

Page 5: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

5555

Relational DatabasesJoins

� Result of a natural join

Linda A.MAAcme$10Widget

Linda A.MAAcme$5Thingy

Blecco

Blecco

Vendor

WA

WA

State

Adam P.

Adam P.

Contact

$25

$8

Cost

Foobar

Widget

Product

Relational DatabasesStructured Query Language (SQL)

� Standard language for accessing a relational database, standardized by American National Standards Institute (ANSI); SQL-92

� Open, but not really� Common functions are mostly the same across

products

� Most vendors have proprietary extensions

� Subsets of SQL� Data Definition Language (DDL)

� Data Manipulation Language (DML)

� Data Control Language (DCL)

Page 6: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

6666

Relational DatabasesDDL Examples

� Used to create and modify database objects

CREATE DATABASE BookstoreCREATE DATABASE BookstoreCREATE DATABASE BookstoreCREATE DATABASE Bookstore

CREATE TABLE tBooksCREATE TABLE tBooksCREATE TABLE tBooksCREATE TABLE tBooks

((((

BookID INT IDENTITY(1,1) PRIMARY KEY,BookID INT IDENTITY(1,1) PRIMARY KEY,BookID INT IDENTITY(1,1) PRIMARY KEY,BookID INT IDENTITY(1,1) PRIMARY KEY,

Title VARCHAR(30) NOT NULL,Title VARCHAR(30) NOT NULL,Title VARCHAR(30) NOT NULL,Title VARCHAR(30) NOT NULL,

PubDate DATE NOT NULL,PubDate DATE NOT NULL,PubDate DATE NOT NULL,PubDate DATE NOT NULL,

[Description] VARCHAR(50),[Description] VARCHAR(50),[Description] VARCHAR(50),[Description] VARCHAR(50),

Category INT NOT NULLCategory INT NOT NULLCategory INT NOT NULLCategory INT NOT NULL

))))

Relational DatabasesDML Examples

� Select data to viewSELECT * FROM tAuthorsSELECT * FROM tAuthorsSELECT * FROM tAuthorsSELECT * FROM tAuthors

SELECT AuthID, FirstName, LastName SELECT AuthID, FirstName, LastName SELECT AuthID, FirstName, LastName SELECT AuthID, FirstName, LastName

FROM tAuthorsFROM tAuthorsFROM tAuthorsFROM tAuthors

SELECT AuthID, FirstName, LastName, Phone SELECT AuthID, FirstName, LastName, Phone SELECT AuthID, FirstName, LastName, Phone SELECT AuthID, FirstName, LastName, Phone

FROM tAuthorsFROM tAuthorsFROM tAuthorsFROM tAuthors

WHERE City = ‘Boston’WHERE City = ‘Boston’WHERE City = ‘Boston’WHERE City = ‘Boston’

SELECT FirstName, LastName, Phone SELECT FirstName, LastName, Phone SELECT FirstName, LastName, Phone SELECT FirstName, LastName, Phone

FROM tAuthorsFROM tAuthorsFROM tAuthorsFROM tAuthors

WHERE AuthID = 249WHERE AuthID = 249WHERE AuthID = 249WHERE AuthID = 249

Page 7: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

7777

Relational DatabasesDML Examples

� Using SELECT to join tables

SELECT AuthID, FirstName, LastName, Phone,SELECT AuthID, FirstName, LastName, Phone,SELECT AuthID, FirstName, LastName, Phone,SELECT AuthID, FirstName, LastName, Phone,

BookID, Title, PubDate, Description BookID, Title, PubDate, Description BookID, Title, PubDate, Description BookID, Title, PubDate, Description

FROM tAuthors, tBooksFROM tAuthors, tBooksFROM tAuthors, tBooksFROM tAuthors, tBooks

WHERE tAuthors.AuthID = tBooks.AuthIDWHERE tAuthors.AuthID = tBooks.AuthIDWHERE tAuthors.AuthID = tBooks.AuthIDWHERE tAuthors.AuthID = tBooks.AuthID

SELECT AuthID, FirstName, LastName, Phone,SELECT AuthID, FirstName, LastName, Phone,SELECT AuthID, FirstName, LastName, Phone,SELECT AuthID, FirstName, LastName, Phone,

BookID, Title, PubDate, Description BookID, Title, PubDate, Description BookID, Title, PubDate, Description BookID, Title, PubDate, Description

FROM tAuthors INNER JOIN tBooksFROM tAuthors INNER JOIN tBooksFROM tAuthors INNER JOIN tBooksFROM tAuthors INNER JOIN tBooks

ON tAuthors.AuthID = tBooks.AuthIDON tAuthors.AuthID = tBooks.AuthIDON tAuthors.AuthID = tBooks.AuthIDON tAuthors.AuthID = tBooks.AuthID

Relational DatabasesDML Examples

INSERT INTO tBooksINSERT INTO tBooksINSERT INTO tBooksINSERT INTO tBooks

(Title, PubDate, [Description], Category)(Title, PubDate, [Description], Category)(Title, PubDate, [Description], Category)(Title, PubDate, [Description], Category)

VALUESVALUESVALUESVALUES

(‘Database Design’, GETDATE(), (‘Database Design’, GETDATE(), (‘Database Design’, GETDATE(), (‘Database Design’, GETDATE(),

‘How to design a database’, 3)‘How to design a database’, 3)‘How to design a database’, 3)‘How to design a database’, 3)

UPDATE tAuthorsUPDATE tAuthorsUPDATE tAuthorsUPDATE tAuthors

SET Phone = ‘617SET Phone = ‘617SET Phone = ‘617SET Phone = ‘617----555555555555----1234’1234’1234’1234’

WHERE AuthID = 5WHERE AuthID = 5WHERE AuthID = 5WHERE AuthID = 5

DELETE FROM tAuthorsDELETE FROM tAuthorsDELETE FROM tAuthorsDELETE FROM tAuthors

WHERE AuthID = 5WHERE AuthID = 5WHERE AuthID = 5WHERE AuthID = 5

� Insert, update and delete data

Page 8: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

8888

Relational DatabasesDCL Examples

� Set security options on database objects

GRANT INSERT, UPDATE, DELETEGRANT INSERT, UPDATE, DELETEGRANT INSERT, UPDATE, DELETEGRANT INSERT, UPDATE, DELETE

ON tAuthorsON tAuthorsON tAuthorsON tAuthors

TO Mary, JohnTO Mary, JohnTO Mary, JohnTO Mary, John

REVOKE CREATE TABLE FROM JoeREVOKE CREATE TABLE FROM JoeREVOKE CREATE TABLE FROM JoeREVOKE CREATE TABLE FROM Joe

DENY ALLDENY ALLDENY ALLDENY ALL

ON tAuthors, tBooksON tAuthors, tBooksON tAuthors, tBooksON tAuthors, tBooks

TO SallyTO SallyTO SallyTO Sally

Relational DatabasesViews

� A view is a virtual table

� Abstracts the underlying table structures

� Abstracts a (possibly complex) query

� Provides security abstraction from table

� In SQL Server, a view can be

� Indexed

� Updated and inserted into

Page 9: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

9999

Relational Databases View Definition Example

CREATE VIEW vwCustomerOrders ASCREATE VIEW vwCustomerOrders ASCREATE VIEW vwCustomerOrders ASCREATE VIEW vwCustomerOrders AS

SELECT o.OrderId, c.CompanyNameSELECT o.OrderId, c.CompanyNameSELECT o.OrderId, c.CompanyNameSELECT o.OrderId, c.CompanyName

FROM Customers cFROM Customers cFROM Customers cFROM Customers c

INNER JOIN Orders o INNER JOIN Orders o INNER JOIN Orders o INNER JOIN Orders o

ON c.CustomerID = O.CustomerIDON c.CustomerID = O.CustomerIDON c.CustomerID = O.CustomerIDON c.CustomerID = O.CustomerID

ORDER BY o.OrderIdORDER BY o.OrderIdORDER BY o.OrderIdORDER BY o.OrderId

Relational DatabasesView Usage Example

SELECT * SELECT * SELECT * SELECT *

FROM vwCustomerOrders FROM vwCustomerOrders FROM vwCustomerOrders FROM vwCustomerOrders

WHERE CompanyName = 'My Favorite Customer'WHERE CompanyName = 'My Favorite Customer'WHERE CompanyName = 'My Favorite Customer'WHERE CompanyName = 'My Favorite Customer'

OrderIdOrderIdOrderIdOrderId CompanyNameCompanyNameCompanyNameCompanyName

101 My Favorite Customer

137 My Favorite Customer

Page 10: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

11110000

Relational DatabasesStored Procedures

� A group of SQL statements that runs within the database

� Not part of SQL standard

� Provides greater performance

� Can control access to data

� Can accept parameters

� Can return data� Output parameters

� Return values

� Result set

Relational Databases Stored Procedure Example

CREATE PROCEDURE CustOrderHist @CustomerID nchar(5)CREATE PROCEDURE CustOrderHist @CustomerID nchar(5)CREATE PROCEDURE CustOrderHist @CustomerID nchar(5)CREATE PROCEDURE CustOrderHist @CustomerID nchar(5)

ASASASAS

SELECT ProductName, Total=SUM(Quantity)SELECT ProductName, Total=SUM(Quantity)SELECT ProductName, Total=SUM(Quantity)SELECT ProductName, Total=SUM(Quantity)

FROM Products P, [Order Details] OD, FROM Products P, [Order Details] OD, FROM Products P, [Order Details] OD, FROM Products P, [Order Details] OD, Orders O, Customers COrders O, Customers COrders O, Customers COrders O, Customers C

WHERE C.CustomerID = @CustomerIDWHERE C.CustomerID = @CustomerIDWHERE C.CustomerID = @CustomerIDWHERE C.CustomerID = @CustomerID

AND C.CustomerID = O.CustomerIDAND C.CustomerID = O.CustomerIDAND C.CustomerID = O.CustomerIDAND C.CustomerID = O.CustomerID

AND O.OrderID = OD.OrderIDAND O.OrderID = OD.OrderIDAND O.OrderID = OD.OrderIDAND O.OrderID = OD.OrderID

AND OD.ProductID = P.ProductIDAND OD.ProductID = P.ProductIDAND OD.ProductID = P.ProductIDAND OD.ProductID = P.ProductID

GROUP BY ProductNameGROUP BY ProductNameGROUP BY ProductNameGROUP BY ProductName

Page 11: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

11111111

Relational DatabasesStored Procedure Examples

exec CustOrderHist 'alfki'exec CustOrderHist 'alfki'exec CustOrderHist 'alfki'exec CustOrderHist 'alfki'

ProductNameProductNameProductNameProductName TotalTotalTotalTotal

Aniseed Syrup 6

Chartreuse verte 21

... ...

Relational Databases Stored Procedure Examples

� Use RETURN statement to return status

� 0 is default in SQL Server

� Can only be numeric

� Use OUTPUT parameters to return results

RETURN 1RETURN 1RETURN 1RETURN 1

CREATE PROCEDURE MyProcedure @ReturnValue INT OUTPUTCREATE PROCEDURE MyProcedure @ReturnValue INT OUTPUTCREATE PROCEDURE MyProcedure @ReturnValue INT OUTPUTCREATE PROCEDURE MyProcedure @ReturnValue INT OUTPUT

............

SELECT @ReturnValue = ColumnName FROM TableSELECT @ReturnValue = ColumnName FROM TableSELECT @ReturnValue = ColumnName FROM TableSELECT @ReturnValue = ColumnName FROM Table

Page 12: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

11112222

Relational DatabasesTriggers

� Like stored procedures, triggers are code that runs within a database

� Not directly called by a user

� Executed when a specified data modification takes place (INSERT, UPDATE or DELETE)

� Enforces business rules

� FOR AFTER: trigger executes after triggering action completes

� FOR INSTEAD OF: trigger executes in place of triggering action

Relational DatabasesTransactions

� Transaction: a sequence of SQL statements that constitute a logical unit of work

Page 13: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

11113333

Outline

� Databases

� Relational Databases

� ADO.NET Overview

� ADO.NET Classes

ADO.NET OverviewLooking Back

� ODBC (Open Database Connectivity)� Interoperability to a wide range of database management systems

(DBMS)

� Widely accepted API

� Uses SQL as data access language

� OLE DB� Broad access to data, relational and other

� Built on COM

� Not restricted to SQL for retrieving data

� Can use ODBC drivers

� Low-level (C++) interface

� ADO (ActiveX Data Objects)� Simple component-based, object-oriented interface

� Provides a programming model to OLE DB accessible outside of C++

Page 14: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

11114444

ADO.NET OverviewLooking Back

ADO

ODBC ProviderODBC ProviderODBC ProviderODBC Provider Simple ProviderSimple ProviderSimple ProviderSimple Provider Native ProviderNative ProviderNative ProviderNative Provider

OLE DB OLE DB OLE DB OLE DB ProviderProviderProviderProvider

ODBCODBCODBCODBC

ODBC DriverODBC DriverODBC DriverODBC Driver

TextTextTextTextFileFileFileFile

DatabaseDatabaseDatabaseDatabase DatabaseDatabaseDatabaseDatabase

OLE DB OLE DB OLE DB OLE DB ProviderProviderProviderProvider

MainframeMainframeMainframeMainframe

OLE DB

Your Application

ADO.NET OverviewLooking Back

� ADO was designed as a connected, tightly coupled model

� Appropriate for client/server architectures

� Primarily relational (not hierarchical like XML)

� Object design is not well factored

� Too many ways to do the same thing

� Objects try to do too much

� Not originally designed for a distributed, n-tier environment

Page 15: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

11115555

ADO.NET OverviewWhat 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 OverviewADO.NET Goals

� Well-factored design

� Highly scaleable through a robust disconnected model

� Rich XML support (hierarchical as well as relational)

� Data access over HTTP

� Maintain familiar ADO programming model

� Keep ADO available via .NET COM interoperability

Page 16: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

11116666

ADO.NET OverviewManaged 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

SQL Managed ProviderSQL Managed ProviderSQL Managed ProviderSQL Managed Provider

SQL ServerSQL ServerSQL ServerSQL ServerDatabaseDatabaseDatabaseDatabase

ADO.NET OverviewManaged Providers

ADO.NET Managed Provider

ADO Managed ProviderADO Managed ProviderADO Managed ProviderADO Managed Provider

OLE DB OLE DB OLE DB OLE DB ProviderProviderProviderProvider

DatabaseDatabaseDatabaseDatabase

Your Application

Page 17: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

11117777

ADO.NET OverviewData Access Styles

� Connected: Forward-only, read-only

� Application issues query then reads back results and processes them

� “Firehose” cursor

� DataReader object

� Disconnected

� Application issues query then retrieves and stores results for processing

� Minimizes time connected to database

� DataSet object

ADO.NET OverviewData 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

� Complex controls for displaying a data structure

<asp:Label runat=server Text='<%# CustList(0).FirstName %>'/><asp:Label runat=server Text='<%# CustList(0).FirstName %>'/><asp:Label runat=server Text='<%# CustList(0).FirstName %>'/><asp:Label runat=server Text='<%# CustList(0).FirstName %>'/>

Page 18: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

11118888

Outline

� Database Theory and History

� Relational Database Concepts and Terminology

� ADO.NET Overview

� ADO.NET Classes

ADO.NET ClassesIDbConnectionIDbConnectionIDbConnectionIDbConnection Interface

� Creates a unique session with a data source

� Implemented by SqlConnection and OleDbConnection

� Functionality

� Open, close connections

� Begin transactions

� IDbTransaction provide Commit and Rollback methods

� Used in conjunction with IDbCommand and IDataAdapter objects

� Additional properties, methods and collections depend on the provider

Page 19: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

11119999

ADO.NET Classes IDbCommandIDbCommandIDbCommandIDbCommand Interface

� Represents a statement to be sent to a data source� Usually, but not necessarily SQL

� Implemented by OleDbCommand and SqlCommand

� Functionality� Define statement to execute

� Execute statement

� Pass and retrieve parameters

� Create a prepared (compiled) version of command

� ExecuteReader returns rows, ExecuteNonQuerydoesn’t, ExecuteScalar returns single value

� Additional properties, methods and collections depend on the provider

ADO.NET Classes IDataReaderIDataReaderIDataReaderIDataReader Interface

� Forward-only, read-only (“fire hose”) access to a stream of data

� Implemented by SqlDataReader and OleDbDataReader

� Created via ExecuteReader method of IDbCommand

� Operations on associated IDbConnectionobject disallowed until reader is closed

Page 20: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

22220000

ADO.NET Classes System.Data.OleDbSystem.Data.OleDbSystem.Data.OleDbSystem.Data.OleDb Namespace

� Managed provider for use with OLEDB providers

� SQLOLEDB (SQL Server) – use System.Data.SQL

� MSDAORA (Oracle)

� JOLT (Jet)

� OLEDB for ODBC providers

� OleDbConnection, OleDbCommand and OleDbDataReader classes

� Classes for error handling

� Classes for connection pooling

ADO.NET Classes DataReaderDataReaderDataReaderDataReader Example

string sConnString = “Provider=SQLOLEDB.1;” +string sConnString = “Provider=SQLOLEDB.1;” +string sConnString = “Provider=SQLOLEDB.1;” +string sConnString = “Provider=SQLOLEDB.1;” +

“User ID=sa;Initial Catalog=Northwind;” +“User ID=sa;Initial Catalog=Northwind;” +“User ID=sa;Initial Catalog=Northwind;” +“User ID=sa;Initial Catalog=Northwind;” +

“Data Source=MYSERVER”;“Data Source=MYSERVER”;“Data Source=MYSERVER”;“Data Source=MYSERVER”;

OleDbConnection conn = new OleDbConnection(sConnString);OleDbConnection conn = new OleDbConnection(sConnString);OleDbConnection conn = new OleDbConnection(sConnString);OleDbConnection conn = new OleDbConnection(sConnString);

conn.Open();conn.Open();conn.Open();conn.Open();

string sQueryString = “SELECT CompanyName FROM Customers”;string sQueryString = “SELECT CompanyName FROM Customers”;string sQueryString = “SELECT CompanyName FROM Customers”;string sQueryString = “SELECT CompanyName FROM Customers”;

OleDbCommand myCommand = new OleDbCommand(sQueryString, conn);OleDbCommand myCommand = new OleDbCommand(sQueryString, conn);OleDbCommand myCommand = new OleDbCommand(sQueryString, conn);OleDbCommand myCommand = new OleDbCommand(sQueryString, conn);

OleDbDataReader myReader = myCommand.ExecuteReader();OleDbDataReader myReader = myCommand.ExecuteReader();OleDbDataReader myReader = myCommand.ExecuteReader();OleDbDataReader myReader = myCommand.ExecuteReader();

while (myReader.Read()) {while (myReader.Read()) {while (myReader.Read()) {while (myReader.Read()) {

Console.WriteLine(myReader.GetString(0));Console.WriteLine(myReader.GetString(0));Console.WriteLine(myReader.GetString(0));Console.WriteLine(myReader.GetString(0));

}}}}

myReader.Close();myReader.Close();myReader.Close();myReader.Close();

conn.Close();conn.Close();conn.Close();conn.Close();

Page 21: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

22221111

ADO.NET ClassesSystem.DataSystem.DataSystem.DataSystem.Data Namespace

� Contains the core classes of the ADO.NET architecture

� Disconnected DataSet is central

� Supports all types of applications

� Internet based

� ASP.NET

� XML

� Windows forms based

ADO.NET ClassesSystem.DataSystem.DataSystem.DataSystem.Data Namespace

� Contains classes used by or derived from managed providers

� IDbConnection, IDbCommand, IDbDataReader

Page 22: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

22222222

DataAdapter & DataSet

ADO.NET ClassesDataSetDataSetDataSetDataSet

� A collection of tables

� Has no knowledge of the source of the data

� Keeps track of all relationships among tables

� Rich programming model (has objects for tables, columns, relationships, and so on)

� Remembers original and current state of data

� Can dynamically modify data and metadata

� Native serialization format is XML

� Located in System.Data

Page 23: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

22223333

ADO.NET Classes DataSetDataSetDataSetDataSet

DataSetDataSetDataSetDataSet

DataTableDataTableDataTableDataTable

DataRelationDataRelationDataRelationDataRelation

DataRowDataRowDataRowDataRow

DataColumnDataColumnDataColumnDataColumn

ADO.NET ClassesSystem.Data.SqlClientSystem.Data.SqlClientSystem.Data.SqlClientSystem.Data.SqlClient Namespace

� Managed provider native to SQL Server

� Built on TDS (Tabular Data Stream) for high performance in SQL Server

� SqlConnection, SqlCommand and SqlDataReader classes

� Classes for � Error handling

� Connection pooling (implicitly enabled by default )

� System.Data.SqlTypes provides classes for native SQL Server data types

Page 24: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

22224444

ADO.NET Classes IDataAdapterIDataAdapterIDataAdapterIDataAdapter Interface

� Populates or sends updates to a DataSet

� Implemented by OleDbDataAdapter and SqlDataAdapter

� Not connection based

� Represents an asynchronous approach

� A superset of a command object

� Contains four default command objects for Select, Insert, Update, and Delete

ADO.NET Classes DataSetDataSetDataSetDataSet Example

string sConnString = “Persist Security Info=False;” +string sConnString = “Persist Security Info=False;” +string sConnString = “Persist Security Info=False;” +string sConnString = “Persist Security Info=False;” +

“User ID=sa;Initial Catalog=Northwind;” +“User ID=sa;Initial Catalog=Northwind;” +“User ID=sa;Initial Catalog=Northwind;” +“User ID=sa;Initial Catalog=Northwind;” +

“Data Source=MYSERVER”;“Data Source=MYSERVER”;“Data Source=MYSERVER”;“Data Source=MYSERVER”;

SqlConnection conn = new SqlConnection(sConnString);SqlConnection conn = new SqlConnection(sConnString);SqlConnection conn = new SqlConnection(sConnString);SqlConnection conn = new SqlConnection(sConnString);

conn.Open();conn.Open();conn.Open();conn.Open();

string sQueryString = “SELECT CompanyName FROM Customers”;string sQueryString = “SELECT CompanyName FROM Customers”;string sQueryString = “SELECT CompanyName FROM Customers”;string sQueryString = “SELECT CompanyName FROM Customers”;

SqlDataAdapter myDSAdapter = new SqlDataAdapter();SqlDataAdapter myDSAdapter = new SqlDataAdapter();SqlDataAdapter myDSAdapter = new SqlDataAdapter();SqlDataAdapter myDSAdapter = new SqlDataAdapter();

DataSet myDataSet = new DataSet();DataSet myDataSet = new DataSet();DataSet myDataSet = new DataSet();DataSet myDataSet = new DataSet();

myDSAdapter.SelectCommand = new SqlCommand(sQueryString, conn);myDSAdapter.SelectCommand = new SqlCommand(sQueryString, conn);myDSAdapter.SelectCommand = new SqlCommand(sQueryString, conn);myDSAdapter.SelectCommand = new SqlCommand(sQueryString, conn);

myDSAdapter.Fill(myDataSet);myDSAdapter.Fill(myDataSet);myDSAdapter.Fill(myDataSet);myDSAdapter.Fill(myDataSet);

conn.Close();conn.Close();conn.Close();conn.Close();

Page 25: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

22225555

ADO.NET Classes DataTableDataTableDataTableDataTable

� In-memory object representing one table

� Columns

� Rows

� Schema defined by Columns collection

� Data integrity provided through Constraintobjects

� Public events

� Modifying/deleting rows

� Modifying columns

ADO.NET Classes DataColumnDataColumnDataColumnDataColumn

� Fundamental building block of a DataTableschema (contained in Columns collection)

� Defines what type of data may be entered (via DataType property)

� Other important properties include AllowNull, Unique, and ReadOnly

� Can contain Constraints (a collection on DataTable)

� Can contain Relations (collection on DataSet)

Page 26: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

22226666

ADO.NET Classes DataRowDataRowDataRowDataRow

� Represents data in a DataTable (contained in Rows collection)

� Conforms to schema defined by DataColumns

� Properties for determining row state (e.g., new, changed, deleted, etc.)

� All additions/modifications “committed” with AcceptChanges method of DataTable

ADO.NET Classes DataRelationDataRelationDataRelationDataRelation

� Relates two DataTables via DataColumns

� DataType value of both DataColumns must be identical

� Updates can be cascaded to child DataTables

� Modifications that invalidate the relation are disallowed

Page 27: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

22227777

ADO.NET Classes Creating a DataSetDataSetDataSetDataSet in Code

DataSet dataset = new DataSet();DataSet dataset = new DataSet();DataSet dataset = new DataSet();DataSet dataset = new DataSet();dataset.DataSetName = “BookAuthors”;dataset.DataSetName = “BookAuthors”;dataset.DataSetName = “BookAuthors”;dataset.DataSetName = “BookAuthors”;

DataTable authors = new DataTable(“Author”);DataTable authors = new DataTable(“Author”);DataTable authors = new DataTable(“Author”);DataTable authors = new DataTable(“Author”);DataTable books = new DataTable(“Book”);DataTable books = new DataTable(“Book”);DataTable books = new DataTable(“Book”);DataTable books = new DataTable(“Book”);

� Create DataSet

� Define tables

ADO.NET Classes Creating a DataSetDataSetDataSetDataSet in Code

� Define columns

� Define keysDataColumn id = authors.Columns.Add("ID", typeof(Int32));DataColumn id = authors.Columns.Add("ID", typeof(Int32));DataColumn id = authors.Columns.Add("ID", typeof(Int32));DataColumn id = authors.Columns.Add("ID", typeof(Int32));id.AutoIncrement = true;id.AutoIncrement = true;id.AutoIncrement = true;id.AutoIncrement = true;authors.PrimaryKey = new DataColumn[] {id};authors.PrimaryKey = new DataColumn[] {id};authors.PrimaryKey = new DataColumn[] {id};authors.PrimaryKey = new DataColumn[] {id};

DataColumn name DataColumn name DataColumn name DataColumn name = new authors.Columns.Add("Name",typeof(String));= new authors.Columns.Add("Name",typeof(String));= new authors.Columns.Add("Name",typeof(String));= new authors.Columns.Add("Name",typeof(String));

DataColumn isbn = books.Columns.Add("ISBN", typeof(String));DataColumn isbn = books.Columns.Add("ISBN", typeof(String));DataColumn isbn = books.Columns.Add("ISBN", typeof(String));DataColumn isbn = books.Columns.Add("ISBN", typeof(String));books.PrimaryKey = new DataColumn[] {isbn};books.PrimaryKey = new DataColumn[] {isbn};books.PrimaryKey = new DataColumn[] {isbn};books.PrimaryKey = new DataColumn[] {isbn};

DataColumn title = books.Columns.Add("Title", typeof(String));DataColumn title = books.Columns.Add("Title", typeof(String));DataColumn title = books.Columns.Add("Title", typeof(String));DataColumn title = books.Columns.Add("Title", typeof(String));DataColumn authid = books.Columns.Add(“AuthID”,typeof(Int32));DataColumn authid = books.Columns.Add(“AuthID”,typeof(Int32));DataColumn authid = books.Columns.Add(“AuthID”,typeof(Int32));DataColumn authid = books.Columns.Add(“AuthID”,typeof(Int32));DataColumn[] foreignkey = new DataColumn[] {authid};DataColumn[] foreignkey = new DataColumn[] {authid};DataColumn[] foreignkey = new DataColumn[] {authid};DataColumn[] foreignkey = new DataColumn[] {authid};

Page 28: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

22228888

ADO.NET Classes Creating a DataSetDataSetDataSetDataSet in Code

� Add the tables to the DataSet

dataset.Tables.Add (authors);dataset.Tables.Add (authors);dataset.Tables.Add (authors);dataset.Tables.Add (authors);dataset.Tables.Add (books);dataset.Tables.Add (books);dataset.Tables.Add (books);dataset.Tables.Add (books);

ADO.NET Classes Creating a DataSetDataSetDataSetDataSet in Code

� Add data and save the DataSetDataRow shkspr = authors.NewRow();DataRow shkspr = authors.NewRow();DataRow shkspr = authors.NewRow();DataRow shkspr = authors.NewRow();shkspr["Name"] = "William Shakespeare";shkspr["Name"] = "William Shakespeare";shkspr["Name"] = "William Shakespeare";shkspr["Name"] = "William Shakespeare";authors.Rows.Add(shkspr);authors.Rows.Add(shkspr);authors.Rows.Add(shkspr);authors.Rows.Add(shkspr);

DataRow row = books.NewRow();DataRow row = books.NewRow();DataRow row = books.NewRow();DataRow row = books.NewRow();row["AuthID"] = shkspr["ID"];row["AuthID"] = shkspr["ID"];row["AuthID"] = shkspr["ID"];row["AuthID"] = shkspr["ID"];row["ISBN"] = "1000row["ISBN"] = "1000row["ISBN"] = "1000row["ISBN"] = "1000----XYZ";XYZ";XYZ";XYZ";row["Title"] = "MacBeth";row["Title"] = "MacBeth";row["Title"] = "MacBeth";row["Title"] = "MacBeth";books.Rows.Add(row);books.Rows.Add(row);books.Rows.Add(row);books.Rows.Add(row);

dataset.AcceptChanges();dataset.AcceptChanges();dataset.AcceptChanges();dataset.AcceptChanges();

Page 29: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

22229999

ADO.NET ClassesTyped DataSetDataSetDataSetDataSets

� Typed DataSet

� Derived from base DataSet class

� Uses XML schema to generate new class

� Tables, columns, etc. compiled into new class

� Untyped DataSet (*.dbml)

� No built-in schema

� Tables, columns, etc. exposed only as collections

ds.Customers.FirstNameds.Customers.FirstNameds.Customers.FirstNameds.Customers.FirstName

ds.Tables[“Customers”].Rows[0][“FirstName”]ds.Tables[“Customers”].Rows[0][“FirstName”]ds.Tables[“Customers”].Rows[0][“FirstName”]ds.Tables[“Customers”].Rows[0][“FirstName”]

ADO.NET Classes Errors and Exceptions

� Error class� Contains information on an error or warning returned

by data source

� Created and managed by Errors class

� Errors class� Contains all errors generated by an adapter

� Created by Exception class

� Exception class� Created whenever an unhandled error occurs

� Always contains at least one Error instance

Page 30: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

33330000

ADO.NET Classes Errors and Exceptions Example

try {try {try {try {

DataTable myTable = new DataTable();DataTable myTable = new DataTable();DataTable myTable = new DataTable();DataTable myTable = new DataTable();

myTable.Columns.Add(“myCol”);myTable.Columns.Add(“myCol”);myTable.Columns.Add(“myCol”);myTable.Columns.Add(“myCol”);

myTable.Columns.Add(“myCol”);myTable.Columns.Add(“myCol”);myTable.Columns.Add(“myCol”);myTable.Columns.Add(“myCol”);

//whoops!//whoops!//whoops!//whoops!

}}}}

catch (DataException myException) {catch (DataException myException) {catch (DataException myException) {catch (DataException myException) {

Console.WriteLine ("Message: " + myException.Message + "Console.WriteLine ("Message: " + myException.Message + "Console.WriteLine ("Message: " + myException.Message + "Console.WriteLine ("Message: " + myException.Message + "\\\\n" +n" +n" +n" +

"Source: " + myException.Source + ""Source: " + myException.Source + ""Source: " + myException.Source + ""Source: " + myException.Source + "\\\\n" +n" +n" +n" +

“Stack Trace: " + myException.StackTrace + "“Stack Trace: " + myException.StackTrace + "“Stack Trace: " + myException.StackTrace + "“Stack Trace: " + myException.StackTrace + "\\\\n");n");n");n");

} } } }

Installing SQL Server 2012 Express Management Studio

� Download and install:

� SQL Server 2012 Express Management Studio Express

� Create LocalDB instance:

Sqllocaldb.exe create “SqlExpress”

� Start the LocalDB instance

Sqllocaldb.exe start “SqlExpress”

� Use Management Studio to create new database (choose the folder on the file system)

� Add the connection to (localdb)\SqlExpress to the server explorer in Visual Studio and start using the database from Visual Studio (e.g., Data-Binding, etc.)

Page 31: Outline - wmich.edualfuqaha/summer13/cs5950/... · Select data to view ... AND OD.ProductID = P.ProductID GROUP BY ProductName. 5/29/2013 111111 ... Use RETURN statement to return

5/29/20135/29/20135/29/20135/29/2013

33331111

Connection Strings

� Use http://www.ConnectionStrings.com to prepare connection strings.