Chapter 12 ADO.NET Yingcai Xiao. Introduction to Database.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 14: Advanced Topics: DBMS, SQL, and ASP.NET
Chapter 12 Database Connectivity with ASP.NET JavaScript, Third Edition.
Objective In this session we will discuss about : What is ADO. NET ?
ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.
ASP.NET Programming with C# and SQL Server First Edition
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 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.
Web Server Administration Chapter 7 Installing and Testing a Programming Environment.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
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.
CS795/895: Introduction. Topics Distributed Systems –Availability –Performance –Web Services Security –Authentication –Authorization –Confidentiality.
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.
Database, SQL, and ADO.NET- Part 1 Session 11 Mata kuliah: M0874 – Programming II Tahun: 2010.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ADO.Net Basics Ruwan Wijesinghe Trainer.
Objectives In this lesson, you will learn to: *Identify the need for ADO.NET *Identify the features of ADO.NET *Identify the components of the ADO.NET.
ASP.NET Rina Zviel-Girshin Lecture 5
Module 9: Accessing Relational Data Using Microsoft Visual Studio.NET.
Session 8: ADO.NET. Overview Overview of ADO.NET What is ADO.NET? Using Namespaces The ADO.NET Object Model What is a DataSet? Accessing Data with ADO.NET.
Module 7: Accessing Data by Using ADO.NET
Christopher M. Pascucci.NET Programming: Databases & 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:
Object Oriented Software Development 10. Persistent Storage.
Presented by Joseph J. Sarna Jr. JJS Systems, LLC
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
An Introduction to ADO.Net Marmagna Desai.NET Seminar, Fall-2003.
C# Programming in Depth Prof. Dr. Bertrand Meyer March 2007 – May 2007 Chair of Software Engineering Lecture 10: Database Lisa (Ling) Liu.
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.
Building Informix Data- Driven Applications with.Net Sean R. Durity Manager of IT CornerCap Investment Counsel Informix User Forum 2006 Washington, D.C.
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.
Module 3: Working with Local Data. Overview Using DataSets Using XML Using SQL Server CE.
1 11/15/05CS360 Windows Programming ADO.NET Continued.
HNDIT Rapid Application Development
2314 – Programming Language Concepts Introduction to ADO.NET.
Database Connectivity with ASP.NET. 2 Introduction Web pages commonly used to: –Gather information stored on a Web server database Most server-side scripting.
ADO.NET FUNDAMENTALS BEGINNING ASP.NET 3.5 IN C#.
Module 4 Introduction ADO.NET.
Active Data Objects Using.Net ADO.Net Farooq Ahmed Amna Umber Summayya Shehzad.
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
C# 1 CSC 298 ADO.NET. C# 2 ADO.NET  A data access technology that maps very well to the world of the web (disconnected architecture)  data is retrieved.
 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
Introduction to Database Processing with ADO.NET
Introduction to Database Processing with ADO.NET
ADO.NET and Stored Procedures
ADO.NET Framework.
Programming the Web Using ASP.Net
Lecture 6 VB.Net SQL Server.
Introduction to Database
ADO.Net and Stored Procedures
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:

Chapter 12 ADO.NET Yingcai Xiao

Introduction to Database

 Computer Science: the science of data processing using a computational device.  Database (DB): a persistent store of data in a compact, secure, easy-and-fast-to-retrieve form.  Database Engine: a software program that creates and manages databases. (e.g. MS Jet Engine)  Database Management System (DBMS): a database engine plus user interfaces and other supporting software.  DBMS Examples: Oracle, DB2 (IBM), Sybase, Informix, Microsoft SQL Server, Microsoft Access, MySQL (public domain), …  Database Server: a DBMS that provides data to its remote clients.. Definitions

DBMS / Database ServerApplication Server WEB S E R V E R WEB C L I E N T Database User Interface Database Engine Supporting Software Database API Application Logic App User Interface Architecture of a Four-Tier Application

DBMS Example: SQL Server By Microsoft Needs runtime license Best fit for.NET Features Free version: SQL Server Express Available in MSDNAA.

DBMS Example: MySQL By MySQL AB (part of Sun after 1/16/08. Sun has been merged into Oracle.) Free: No need of runtime license Not the best fit for.NET Installed on db1.cs.uakron.edu How to install it at home: Installation.html

Data Format in the Database  Database Table: data are stored in a database as “tables”. Each row of a table is called a record, each column of a table is called an attribute. Each needs to have a “key” attribute(s). Each record needs to have a unique key value. PhoneBook (Database Table Name) NameOfficeHomeCell Tom John …………  Database schema: meta data for databases, defining tables and their attributes.

Database Schema, Language, API  Database schema: meta data for databases, defining tables and their attributes. (UDT, like classes)  SQL (Structured Query Language): the de facto standard language for database.  Database API: application programming interface to DBMSs.

SQL  SQL: Structured Query Language, a standardized language for accessing and manipulating databases.  The Select-From-Where Clause: Select Office From PhoneBook Where Name=’Tom’; Select * From PhoneBook;  Three Parts of SQL:  Query: data retrieval  DML - Data Manipulation Language: inserting, deleting, updating, …  DDL - Data Definition Language: table creation, alteration and drop.

SQL Example CREATE DATABASE pubs; USE pubs; CREATE TABLE authors ( au_id varchar(11) NOT NULL, au_lname varchar(40) NOT NULL, au_fname varchar(20) NOT NULL, phone char(12) NOT NULL DEFAULT 'UNKNOWN', address varchar(40) NULL, city varchar(20) NULL, state char(2) NULL, zip char(5) NULL, contract bit NOT NULL, PRIMARY KEY(au_id) );

SQL Example insert authors values(' ', 'Bennet', 'Abraham', ' ', '6223 Bateman St.', 'Berkeley', 'CA', '94705', 1); insert authors values(' ', 'Green', 'Marjorie', ' ', '309 63rd St. #411', 'Oakland', 'CA', '94618', 1);

Database Programming

ADO.NET ADO.NET is the database API for managed applications (application servers) to talk to database servers (DBMS: Database Management Systems).  a database API for managed applications;  a set of classes in.NET FCL System.Data namespace;  designed to work over the Web;  integrates effortlessly with XML;  maps very well to stateless, text-based protocol HTTP;  accesses databases through modules known as data providers ( a set of APIs that make the accesses easy to program).

1.The SQL Server.NET provider  interfaces to Microsoft SQL Server (7.0 or later)  all managed code  code runs faster  code not portable to other databases 2.The OLE DB.NET provider  OLE: Object Linking and Imbedding  interfaces to databases through unmanaged OLE DB providers: SQLOLEDB for SQL Server (6.5 or earlier), MSDAORA for Oracle and Microsoft, Jet.OLEDB.4.0 for Microsoft Jet database engine.  code runs slower  code portable to other databases Two Data Providers

The System.Data.SqlClient and System.Data.OleDb Namespaces Classes in System.Data.SqlClient are for SQL Server.NET using System.Data.SqlClient; SqlConnection conn = new SqlConnection ("server=localhost;database=pubs;uid=sa;pwd="); try { conn.Open (); SqlCommand cmd = new SqlCommand ("select * from titles", conn); SqlDataReader reader = cmd.ExecuteReader (); while (reader.Read ()) Console.WriteLine (reader["title"]); } catch (SqlException ex) { Console.WriteLine (ex.Message); } finally { conn.Close (); }

The System.Data.SqlClient and System.Data.OleDb Namespaces Classes in System.Data.OleDb are for OLE DB.NET using System.Data.OleDb; OleDbConnection conn = new OleDbConnection("provider=sqloledb;server=localhost;dat abase=pubs;uid=sa;pwd="); try { conn.Open (); OleDbCommand cmd = new OleDbCommand ("select * from titles", conn); OleDbDataReader reader = cmd.ExecuteReader (); while (reader.Read ()) Console.WriteLine (reader["title"]); } catch (OleDbException ex) { Console.WriteLine (ex.Message); } finally { conn.Close (); }

Pattern of database programming  Create a connection object.  Open the connection.  Create a command object.  Execute the command.  Access the data. Close the connection.

A mini enterprise application Congo (C9) Congo: A virtual storefront for an online bookseller. Related to: database => data grid => shopping cart Forms: Database supported, web based security. Examples\C9\Congo-MySQL Deployment: Output format in C#

Structure of an ASP.NET Web Application An ASP.NET application.  The Web.config File To support XCOPY installs— to install applications by copying them to a directory and uninstall them by deleting the files and directories.

<% if (Session.IsNewSession || Session["Count"] == null) { Session["Count"] = 1; Response.Write ("Welcome! Because this is your first visit to this site, a new session has been created for you. Your session ID is " + Session.SessionID + "."); } else { Session["Count"] = (int) Session["Count"] + 1; Response.Write ("You have visited this site " + Session["Count"] + " times. Your session ID is still " + Session.SessionID + "."); } %> Using Session State

Pattern of database programming  Create a connection object.  Open the connection.  Create a command object.  Execute the command.  Access the data. Close the connection.

Connections, Commands, and DataReaders Connection objects represent physical connections to a database. SqlConnection or OleDbConnection Command objects represent the commands performed on a database. SqlCommand or OleDbCommand DataReader objects represent the data obtained by the commands. SqlDataReader or OleDbDataReader

Connection Objects The SqlConnection Class The ConnectionString SqlConnection conn = new SqlConnection (); conn.ConnectionString = "server=localhost;database=pubs;uid=sa;pwd="; or SqlConnection conn = new SqlConnection ("server=localhost;database=pubs;uid=sa;pwd="); Errors in the connection string only throws exceptions at runtime.

Server Server=localhost or Server=(local) or Data Source=(local) SQL Server permits different instances of servers to be installed on a given machine. server=db1 (an database server computer named “db1” at the CS department of UA) server=hawkeye\wintellect (an instance of SQL Server named Wintellect on a remote machine named Hawkeye) Database or Initial Catalog: database name (e.g. Pubs) UID or User ID, Pwd: tempdb, tempdb

 Min Pool Size and Max Pool Size, the size of the connection pool (the defaults are 0 and 100)  Integrated Security: default to false, otherwise uses Windows access tokens for authentication.  Connect Timeout: how many seconds to wait for a connection to open (default=15). SqlConnection conn = new SqlConnection ("server=hawkeye\wintellect;database=pubs;uid=sa;pwd=;" + "min pool size=10;max pool size=50;connect timeout=10"); Server

Exceptions and Closing Open Connections  Exceptions should never go uncaught, and open connections should always be closed before terminating. (Calling Close on a connection that’s not open isn’t harmful.) SqlConnection conn = new SqlConnection ("server=localhost;database=pubs;uid=sa;pwd="); //before try block try {conn.Open (); // TODO: Use the connection } catch (SqlException e) { Console.WriteLine (e.Message); // TODO: Handle the exception } finally { conn.Close ();}

Command Classes: SqlCommand and OleDbCommand. –Encapsulate SQL commands performed on a database. –Rely on connections established. –Include methods to execute the commands encapsulated inside. Example, delete a record from the Pubs database’s “Titles” table using an SQL DELETE command: SqlCommand cmd = new SqlCommand ("delete from titles where title_id = 'BU1032'", conn); cmd.CommandTimeout = 10; // Allow 10 seconds, default 30. cmd.ExecuteNonQuery (); // Execute the command

The ExecuteNonQuery Method For executing DML and DDL commands: CREATE, INSERT, UPDATE, DELETE, … Not getting any data back. Examples: SqlCommand cmd = new SqlCommand ("create database MyDatabase", conn); cmd.ExecuteNonQuery (); SqlCommand cmd = new SqlCommand ("create table titles …", conn); cmd.ExecuteNonQuery (); SqlCommand cmd = new SqlCommand ("insert into titles (title_id, title, type, pubdate) " + "values ('JP1001', 'Programming Microsoft.NET', " + "'business', 'May 2002')", conn); cmd.ExecuteNonQuery ();

The ExecuteNonQuery Method SqlCommand cmd = new SqlCommand ("update titles set title_id = 'JP2002' " + "where title_id = 'JP1001'", conn); cmd.ExecuteNonQuery (); SqlCommand cmd = new SqlCommand ("delete from titles where title_id = 'JP2002'", conn); cmd.ExecuteNonQuery ();

The ExecuteScalar Method Executes a query command and returns a single value in the result set, such as COUNT, AVG, MIN, MAX, and SUM. SqlCommand cmd = new SqlCommand ("select min (price) from titles", conn); decimal amount = (decimal) cmd.ExecuteScalar (); Console.WriteLine ("ExecuteScalar returned {0:c}", amount);

The ExecuteScalar Method  Another common use for ExecuteScalar is to retrieve BLOBs (binary large objects) from databases.  For example, retrieving an image from the “Logo” field of the Pubs database’s “Pub_info” table and encapsulates it in a bitmap: use System.IO; use System.Drawing; use System.Data.SqlClient; SqlCommand cmd = new SqlCommand ("select logo from pub_info where pub_id='0736'", conn); byte[] blob = (byte[]) cmd.ExecuteScalar (); stream.Write (blob, 0, blob.Length); Bitmap bitmap = new Bitmap (stream); stream.Close ();

Write a BLOB to a database. FileStream stream = new FileStream("Logo.jpg", FileMode.Open); byte[] blob = new byte[stream.Length]; stream.Read (blob, 0, (int) stream.Length); stream.Close (); SqlCommand cmd = new SqlCommand ("insert into pub_info (pub_id, logo) values conn); cmd.Parameters.Add blob); cmd.ExecuteNonQuery ();

The ExecuteReader Method  For performing database queries and obtain the results as quickly and efficiently as possible.  Returns a DataReader object.  Pulls back only the data to be “Read” by the DataReader not all records satisfying the query condition. SqlCommand cmd = new SqlCommand ("select * from titles", conn); SqlDataReader reader = cmd.ExecuteReader (); while (reader.Read ()) Console.WriteLine (reader["title"]);  Each call to “Read” returns one row from the result set.  It uses a property indexer to extract the value of the record’s “title” field.  Fields can be referenced by name or by numeric index (0- based).

DataReader  Reads data.  Reads schema (meta data).  Stream-based access to the results of database queries.  Fast and efficient.  Read-only and forward-only.  Closing a DataReader: reader.Close( ) does NOT close the connection, only frees it for others to use.  D-E-F-E-N-S-I-V-E P-R-O-G-R-A-M-M-I-N-G.

DataSets  Set-based Database Accesses  capture an entire query in memory  support backward and forward traversal  edit data and propagate the changes back to the database.

DataSet, DataTable and DataAdapter .NET supports set-based database accesses through three classes:  DataSet: equivalent of an in-memory database. It consists of a collection of DataTables.  DataTables are created by a DataAdapter (SqlDataAdapter and OleDbDataAdapter).  DataSet doesn’t interact with databases directly. DataAdapter reads the physical data sources and fills DataTables and DataSets

DataSets vs. DataReaders  To simply query a database and read through the records one at a time until you find the one you’re looking for, then DataReader is the right tool. DataReaders (1) retrieve only the data that you actually use, and (2) they don’t consume memory by not storing every record that you read, but (3) they can’t iterate backward.  To use all the query results and to iterate backward and forward through a result set, or to cache the result set in memory, use a DataSet.  Many controls that support DataSets are perfectly capable of binding to DataReaders.

DataGrid (GUI) DataGrid is an ASP control for displaying datasets. Database displaying procedure: –Use DataAdapter to get data from the database. –Fill the data into a DataSet –Bind the DataSet to a DataGrid –Select the fields (columns) to be displayed and their header texts.

Example: DataAdapter, DataSet and DataGrid (GUI) <asp:DataGrid ID="MyDataGrid" OnItemCommand="OnItemCommand" RunAt="server"> <asp:BoundColumn HeaderText="Title" DataField="title" /> <asp:BoundColumn HeaderText="Price" DataField="price" DataFormatString="{0:c}"/> <asp:ButtonColumn HeaderText="Action" Text="Add to Cart" CommandName="AddToCart" /> Examples/C9/Congo-MySQL/ViewCart.aspx

Example: DataAdapter, DataSet and DataGrid (GUI) void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { string ConnectString = ConfigurationSettings.AppSettings["connectString"]; MySqlDataAdapter adapter = new MySqlDataAdapter ("select * from titles where price != 0", ConnectString); DataSet ds = new DataSet (); adapter.Fill (ds); MyDataGrid.DataSource = ds; MyDataGrid.DataBind ();//Bind data to GUI }

Transaction Commands  A transaction is a logical unit of operations grouped together.  If one of the operations fails, the others will fail (or be rolled back).  Distributed transactions — transactions that span two or more databases.  The.NET Framework supports distributed transactions.  The.NET supports local transactions (one database):

Transacted Commands // Start a local transaction trans = conn.BeginTransaction (IsolationLevel.Serializable); // Create and initialize a SqlCommand object SqlCommand cmd = new SqlCommand (); cmd.Connection = conn; cmd.Transaction = trans; // Debit $1,000 from account 1111 cmd.CommandText = "update accounts set balance = " + "balance where account_id = '1111'"; cmd.ExecuteNonQuery (); // Credit $1,000 to account 2222 cmd.CommandText = "update accounts set balance = " + "balance where account_id = '2222'"; cmd.ExecuteNonQuery (); // Commit the transaction (commit changes) trans.Commit ();

Transacted Commands  IsolationLevel.Serializable locks down the records while they’re updated so that they can’t be read or written.  Committing the transaction writes the changes to the database.

Uses DataGrid to represent a DataSet in XML DataSet ds = new DataSet (); ds.ReadXml (Server.MapPath ("Bonuses.xml")); MyDataGrid.DataSource = ds;

Summary Database Programming: part of the architecture of a multi- tier application. DB Programming API ADO.NET Data Providers (SQLServer Provider, OLEDB Provider) Connection Commands (NonQuery, Scaler) DataReader DataSet DataAdapter DataGrid Transaction