Data Access with ADO.NET Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz Dr. Dietrich Birngruber Ecolog GmbH Wels ©

Slides:



Advertisements
Similar presentations
17. Data Access ADO.Net Architecture New Features of ADO.NET
Advertisements

Database Connections with ASP.Net
ADO.NET: Working in Disconnected Environment Sergey Baidachni MCT, MCSD, MCDBA.
1 Interface IDbConnection ConnectionString defines data base connection Open and close connection Properties of connection object Creates Command-Object.
Chapter 10 ADO. What is ADO? ADO is a Microsoft technology ADO stands for ActiveX Data Objects ADO is a programming interface to access data in a database.
Introduction to Database Processing with ADO.NET.
1 ADO.NET. 2.NET Framework Data Namespaces System.Data –Base set of classes and interfaces for ADO.NET System.Data.Common –Classes shared by the.NET Data.
ADO. NET. What is “ADO.Net”? ADO.Net is a new object model for dealing with databases in.Net. Although some of the concepts are similar to the classical.
.NET Mobile Application Development Data in Distributed Systems Accessing Data with.NET.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 12 Database Connectivity with ASP.NET JavaScript, Third Edition.
Objective In this session we will discuss about : What is ADO. NET ?
In C# program Before you can start using the ODBC class definitions, you will need to include the right module. using System.Data.Odbc; // ODBC definitions.
ADO.NET – part II August 2004 [ Marmagna Desai]. CONTENTS ADO vs ADO.NET ADO.NET – Managed providers Connecting to Database SqlConnection Selecting Database.
1 Introducing Database Access from Web Applications by Sally Kyvernitis.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
1 UCN Technology: Computer Science: Autumn 2012 ADO.NET 2.0 Architecture DataReader DataSet Connection factory Config file.
1 ASP.NET ASP.NET Rina Zviel-Girshin Lecture 4. 2 Overview Data Binding Data Providers Data Connection Data Manipulations.
Developing Web Applications Using Microsoft ® Visual Studio ® 2008.
Accessing SQL Server and OLE DB from.NET Svetlin Nakov Telerik Corporation
A Simple Introduction. What is ADO.net? First the word ADO stands for ActiveX Data Objects And it is an integral part of.Net Framework of Microsoft hence.
PART 1 CREATING THE PRODUCT CATALOG. ROADMAP FOR THIS CHAPTER To implement the departments list, you’ll start with the database and make your way to the.
Needs for Accessing Database To make your web site more dynamic and maintainable, you can display information on your web pages that are retrieved from.
Databases and Data Access  Introduction to ADO.NET  ADO.NET objects  ADP.NET namespaces  Differences between ADO and ADO.NET.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
.NET Data Access and Manipulation ADO.NET. Overview What is ADO.NET? Disconnected vs. connected data access models ADO.NET Architecture ADO.NET Core Objects.
MySQL Connection using ADO.Net Connecting to MySQL from.NET Languages.
1 Introduction to ADO.NET Microsoft ADO.NET 2.0 Step by Step Rebecca M Riordan Microsoft Press, 2006.
 It is the primary data access model for.Net applications  Next version of ADO  Can be divided into two parts ◦ Providers ◦ DataSets  Resides in System.Data.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ADO.Net Basics Ruwan Wijesinghe Trainer.
Module 7: Accessing Data by Using ADO.NET
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Introduction to ADO.NET ADO.NET - Lesson 01  Training time: 10 minutes  Author:
1 UCN Technology: Computer Science: Autumn 2012 ADO.NET 2.0 Architecture DataReader DataSet Connection factory Config file.
1.Net programmingADO.NETNOEA / PQC ADO.NET Architecture Connection factory Config file DataReader DataSet DataGrid Autogeneration of SQL.
Presented by Joseph J. Sarna Jr. JJS Systems, LLC
An Introduction to ADO.Net Marmagna Desai.NET Seminar, Fall-2003.
ADO.NET connections1 Connecting to SQL Server and Oracle.
 It is the primary data access model for.Net applications  Next version of ADO  Can be divided into two parts ◦ Providers ◦ DataSets  Resides in System.Data.
1 11/10/05CS360 Windows Programming ADO.NET. 2 11/10/05CS360 Windows Programming ADO.NET  Behind every great application is a database manager o Amazon.
Accessing SQL Server and MySQL from.NET and C# Learning & Development Team Telerik Software Academy.
ADO.NET AND STORED PROCEDURES - Swetha Kulkarni. RDBMS ADO.NET Provider  SqlClient  OracleClient  OleDb  ODBC  SqlServerCE System.Data.SqlClient.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
HNDIT Rapid Application Development
ADO.NET FUNDAMENTALS BEGINNING ASP.NET 3.5 IN C#.
Coding ADO.NET Objects: Connection, Command, DataReader.
Module 4 Introduction ADO.NET.
C# .NET Software Development
Active Data Objects Using.Net ADO.Net Farooq Ahmed Amna Umber Summayya Shehzad.
Querying Information in a Database. CONTENTS Relational Database Systems Creating Database with SQL Server Reading Data with LINQ Requirements to Get.
Data Access. ADO.NET ADO.NET is the primary library for building database solutions within the.NET Framework. ADO.NET does not replace ADO. ADO and OLEDB.
ADO .NET from. ADO .NET from “ADO .Net” Evolution/History of ADO.NET MICROSOFT .NET “ADO .Net” Evolution/History of ADO.NET History: Most applications.
.NET Data Access and Manipulation
 ADO.NET is an object-oriented set of libraries that allows you to interact with data sources  Commonly, the data source is a database, but it could.
ASP.NET Programming with C# and SQL Server First Edition
Data Access with ADO.NET
Introduction to ADO.NET
DB Apps Introduction Intro to ADO.NET SQL SoftUni Team DB Apps Intro
Introduction to Database Processing with ADO.NET
Introduction to Database Processing with ADO.NET
ADO.NET and Stored Procedures
ADO.NET Framework.
Lecture 6 VB.Net SQL Server.
ADO.Net and Stored Procedures
Tonga Institute of Higher Education
מתחברים למסד נתונים היכרות עם ADO.Net.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
MySQL Connection using ADO.Net
Chapter 10 ADO.
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
Introduction to Database Programming through ADO. NET
Presentation transcript:

Data Access with ADO.NET Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz Dr. Dietrich Birngruber Ecolog GmbH Wels © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

ADO.NET Introduction Connection-oriented Access Transactions Connectionless Access Database Access with DataAdapter DataSets and DataReader Integration with XML Summary

3 ADO.NET Is the.NET technology for accessing structured data Uniform object oriented interface for different data sources –relational data bases –XML data –other data sources Designed for distributed and Web applications Provides 2 models for data access –connection-oriented –connectionless

4 Idea of Universal Data Access Connection of (object-oriented) programming languages and relational data bases Uniform programming model and API Special implementations for data sources (providers) API provider ODBC MsSql DB2 Oracle Application ?

5 Data Providers Microsoft’s layered architecture for data access SQL-data MS SQL Server, Oracle, Jet, Foxpro,... SQL Server Oracle MySQL ODBC Non-SQL-data Directory Services, Mail, Text, Video,... OLEDB ADO.NET

6 History of Universal Data Access (Microsoft)  ODBC  OLE DB  ADO (ActiveX Data Objects)  ADO.NET ADOADO.NET connection-orientedconnection-oriented + connectionless sequential accesssequential access + main-memory representation with direct access only one table supportedmore than one table supported COM-marshallingXML-marshalling

7 Architecture of ADO.NET connection-orientedconnectionless

8 Connection-oriented versus Connectionless Connection-oriented –Keeps the connection to the data base alive –Always up-to-date data –Intended for applications with: short running transactions only a few parallel access operations Connectionless –No permanent connection to the data source –Data cached in main memory –Changes in main memory may be in conflict with changes in data source –Intended for applications with: many parallel and long lasting access operations (e.g.: Web applications)

9 ADO.NET Assembly and Namespaces Assembly –System.Data.dll Namespaces: –System.Data general types –System.Data.Common classes for implementing providers –System.Data.OleDb OLE DB provider –System.Data.SqlClient Microsoft SQL Server provider –System.Data.SqlTypesd ata types for SQL Server –System.Data.Odbc ODBC provider (since.NET 1.1) –System.Data.OracleClient Oracle provider (since.NET 1.1) –System.Data.SqlServerCe Compact Framework

ADO.NET Introduction Connection-oriented Access Transactions Connectionless Access Database Access with DataAdapter DataSets and DataReader Integration with XML Summary

11 Architecture DbConnection –represents connection to data source DbCommand –represents a SQL command DbTransaction –represents a transaction –commands can be executed within a transaction DataReader –result of a data base query –allows sequential reading of rows

12 Class hierarchy General interfaces IDbConnection IDbCommand IDbTransaction IDataReader Abstract base classes DbConnection DbCommand DbTransaction DbDataReader Special implementations OleDb: implementation for OLEDB Sql :implementation for SQL Server Oracle : implementation for Oracle Odbc : implementation for ODBC SqlCe : implementation for SQL Server CE data base

13 Example: Northwind Database Microsoft Example for SQL Server Reading of table Employees Output of –EmployeesID, LastName, FirstName for all rows of table Employees Run

14 Program Pattern for Connection-oriented Data Access 1.) Declare connection try { 1.) Request connection to database 3.) Process result 2.) Execute SQL commands 4.) Release Resources } catch ( Exception ) { Handle exception } finally { try { 4.) Close connection } catch (Exception) { Handle exception } }

15 Example: EmployeeReader (1) using System; using System.Data; using System.Data.OleDb; public class EmployeeReader { public static void Main() { // continue next page string connStr = "provider=SQLOLEDB; data source=(local)\\NetSDK; " + "initial catalog=Northwind; user id=sa; password=; "; IDbConnection con = null; // declare connection object try { con = new OleDbConnection(connStr); // create connection object con.Open(); // open connection 1)Declare and request connection to database //----- create SQL command IDbCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT EmployeeID, LastName, FirstName FROM Employees"; //----- execute SQL command; result is an OleDbDataReader IDataReader reader = cmd.ExecuteReader(); 2)Execute SQL commands

16 Example: EmployeeReader (2) IDataReader reader = cmd.ExecuteReader(); object[] dataRow = new object[reader.FieldCount]; while (reader.Read()) { int cols = reader.GetValues(dataRow); for (int i = 0; i < cols; i++) Console.Write("| {0} ", dataRow[i]); Console.WriteLine(); } 3)Read and process data rows //----- close reader reader.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } finally { try { if (con != null) // close connection con.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } 4)Release resources and close connection

17 Interface IDbConnection ConnectionString defines data base connection Open and close connection Properties of connection object Creates Command -Object Creates Transaction -Object string ConnectionString {get; set;} string Database {get;} int ConnectionTimeout {get;} ConnectionState State {get;} IDbCommand CreateCommand(); IDbTransaction BeginTransaction(); IDbTransaction BeginTransaction(IsolationLevel lvl); void Open(); void Close();

18 IDbConnection: Property ConnectionString Key-value-pairs separated by semicolon ( ; ) Configuration of the connection –name of the provider –identification of data source –authentication of user –other database-specific settings e.g.: OLEDB: "provider=SQLOLEDB; data source= \\NetSDK; initial catalog=Northwind; user id=sa; password=; " "provider=Microsoft.Jet.OLEDB.4.0;data source=c:\bin\LocalAccess40.mdb;" "provider=MSDAORA; data source=ORACLE8i7; user id=OLEDB; password=OLEDB ;“ e.g.: MS-SQL-Server: "data source=(local)\\NetSDK; initial catalog=Northwind; user id=sa; pooling=false; Integrated Security=SSPI; connection timout=20;" SqlServer Access Oracle

19 DbProviderFactory Writing database-independent programs with DbProviderFactory DbProviderFactory generates set of provider-specific components Provider can be configured in an easy way (e.g. in configuration file) DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); IDbConnection conn = factory.CreateConnection(); IDbCommand cmd = factory.CreateCommand(); cmd.Connection = conn; IDataParameter param = factory.CreateParameter(); create DbProviderFactory for SqlClient create provider specific data access components DBConnection DbCommand DataParameter

20 ConnectionStringBuilder Creation of connection string can be error-prone ConnectionStringBuilder provides support: –Definition with key-value pairs –Validation of syntactical correctness and completeness DbConnectionStringBuilder builder = factory.CreateConnectionStringBuilder(); builder["Server"] = "localhost\\SQLEXPRESS"; builder["Initial Catalog"] = "Northwind"; builder["Integrated Security"] = true; conn.ConnectionString = builder.ConnectionString; conn.Open(); create ConnectionStringBuilder and set values retrieve connection string and configure connection

21 Command Objects Command o bjects define SQL statements or stored procedures Executed for a connection May have parameters May belong to a transaction IDbCommand IDbConnection 1 IDbTransaction 0..1 * IDataParameter * 1

22 Interface IDbCommand CommandText defines SQL statement or stored procedure Connection object Type and timeout properties Creating and accessing parameters Execution of command string CommandText {get; set;} CommandType CommandType {get; set;} int CommandTimeout {get; set;} IDbDataParameter CreateParameter(); IDataParameterCollection Parameters {get;} IDataReader ExecuteReader(); IDataReader ExecuteReader(CommandBehavior b); int ExecuteNonQuery(); object ExecuteScalar(); IDbConnection Connection {get; set;}

23 cmd.CommandText = "SELECT EmployeeID, LastName, FirstName FROM Employees "; IDataReader reader = cmd.ExecuteReader(); Executes the data base query specified in CommandText Result is an IDataReader o bject ExecuteReader Method IDataReader ExecuteReader() IDataReader ExecuteReader( CommandBehavior behavior ); public enum CommandBehavior { CloseConnection, Default, KeyInfo, SchemaOnly, SequentialAccess, SingleResult, SingleRow } Example:

24 cmd.CommandText = "UPDATE Empls SET City = ’Seattle’ WHERE iD=8"; int affectedRows = cmd.ExecuteNonQuery(); Executes the non-query operation specified in CommandText –UPDATE –INSERT –DELETE –CREATE TABLE –… Result is number of affected rows ExecuteNonQuery Method int ExecuteNonQuery(); Example:

25 cmd.CommandText = " SELECT count(*) FROM Employees "; int count = (int) cmd.ExecuteScalar(); Returns the value of the 1 st column of the 1 st row delivered by the query CommandText typically is an aggregate function ExecuteScalar Method object ExecuteScalar(); Example:

26 Parameters Command objects allow input and output parameters Parameter objects specify –Name : name of the parameter –Value : value of the parameter –DbDataType : data type of the parameter –Direction : direction of the parameter Input Output InputOutput ReturnValue IDataParameterCollection Parameters {get;}

27 Working with Parameters 2.Create and add parameter cmd.Parameters.Add( new OleDbType.BigInt)); 3.Assign values and execute command = 1234; cmd.ExecuteNonQuery(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "DELETE FROM Empls WHERE EmployeeID 1.Define SQL command with place holders OLEDB: Identification of parameters by position (notation: "?") SQL Server: Identification of parameters by name ( notation: ) OleDbCommand cmd = new OleDbCommand(); cmd.CommandText = "DELETE FROM Empls WHERE EmployeeID = ?";

28 DataReader ExecuteReader() returns IDataReader object IDataReader allows sequential reading of result (row by row) IDataReader ExecuteReader() IDataReader ExecuteReader( CommandBehavior behavior );

29 Interface IDataReader Read reads next row Access column values using indexers Typed access of column values using access methods Getting meta-information bool Read(); object this[int] {get;} object this[string] {get;} bool GetBoolean(int idx); byte GetByte(int idx);... string GetDataTypeName(int i); string GetName(int idx); int GetOrdinal(string name);...

30 Working with IDataReader object[ ] dataRow = new object[reader.FieldCount]; int cols = reader.GetValues(dataRow); Read column values into an array object val0 = reader[0]; object nameVal = reader["LastName"]; Read column values using indexers string firstName = reader.getString(2); Read column value using typed access method getString } reader.Close(); Close IDataReader object IDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Create IDataReader object and read rows

31 Multiple Active Result Sets (MARS) Usually only one DataReader ADO.NET 2.0 allows several DataReader s in parallel more than one table can be read simultaneously only with SQL Server

32 Example MARS (1) reading Customer und Orders table simultaneously output of the orders for each customer SqlConnection conn = new SqlConnection("...;MultipleActiveResultSets=true"); conn.Open(); //---- creation of two command objects for one connection SqlCommand custCmd = new SqlCommand( "SELECT CustomerId, CompanyName " + "FROM Customers ORDER BY CustomerId", conn); SqlCommand ordCmd = new SqlCommand( "SELECT CustomerId, OrderId, OrderDate " + "FROM Orders ORDER BY CustomerId, OrderDate", conn); //---- execution of commands and creation of two DataReaders IDataReader custRdr = custCmd.ExecuteReader(); IDataReader ordRdr = ordCmd.ExecuteReader();

33 Example MARS (2) … //---- reading data using both DataReaders simultaneously string custId = null; bool moreOrders = ordRdr.Read(); while (custRdr.Read() && moreOrders) { // loop over all customers custId = custRdr.GetString(0); string custName = custRdr.GetString(1); while (moreOrders && custId == ordRdr.GetString(0)) {// loop over orders of customer Console.WriteLine(custName + " ordered " + ordRdr.GetInt32(1) + " at " + ordRdr["OrderDate"]); moreOrders = ordRdr.Read(); } custRdr.Close(); ordRdr.Close();

ADO.NET Introduction Connection-oriented Access Transactions Connectionless Access Database Access with DataAdapter DataSets and DataReader Integration with XML Summary

35 Summary Connection-oriented data access model –for applications with only a few parallel, short running transactions –object-oriented interface abstracts from data source –access to database by SQL commands Connectionless data access model –for applications with many parallel, long running transactions –DataSet as main memory data base –DataAdapter is used as connector to the data source –tight integration with XML –well integrated in the.NET Framework (e.g.: WebForms, WinForms)