Lecture 11: Programmatic Database Access with ADO.NET.

Slides:



Advertisements
Similar presentations
Data Base. Objective Become familiar with database terminology. Create a project to display data for a single database table. Use a DataGrid control.
Advertisements

By Chris Pascucci and FLF
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.
Database Access Using 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.
Coding ADO.NET Objects: Connection, Command, DataReader.
C# Programming: From Problem Analysis to Program Design1 Working with Databases C# Programming: From Problem Analysis to Program Design 3 rd Edition 14.
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.
7. The FCL: files, databases, & data structures. 2 Microsoft Objectives “The Framework Class Library (FCL) contains thousands of classes, from graphics.
From VS C# 2010 Programming, John Allwork 1 VS2010 C# Programming - DB intro 1 Topics – Database Relational - linked tables SQL ADO.NET objects Referencing.
12. WebForms: Web-based GUIs in.NET. 2 Visual Studio.NET Objectives “Drag-and-drop GUI construction has long been the norm for Windows development. With.
ODBC, OLE DB, and ADO Introduction Dr. Ron Eaglin.
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.
Overview of ADO.NET with the.NET Framework Scalable Development, Inc. Building systems today that perform tomorrow.
FEN Data connection DataReader DataSet Bonus info: Concurrency and Database Transactions Embedded SQL.
Joe Hummel, PhD Dept of Mathematics and Computer Science Lake Forest College
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.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
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.
Chapter 13 Database Access Using ADO.NET
Databases and Data Access  Introduction to ADO.NET  ADO.NET objects  ADP.NET namespaces  Differences between ADO and ADO.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.
Architectures Classic Client/Server Architecture Classic Web Architecture N-tier (multi-tier) Architecture FEN Databaser og Modellering.
 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.
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.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
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.
Christopher M. Pascucci.NET Programming: Databases & ADO.NET.
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
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.
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.
C# Programming in Depth Prof. Dr. Bertrand Meyer March 2007 – May 2007 Chair of Software Engineering Lecture 10: Database Lisa (Ling) Liu.
JDS – VB.NET Skill Session Fall 2004 Presented by YUHAO LIN.
Mauricio Featherman, Ph.D. Washington St. University
CIS 375—Web App Dev II ASP.NET 9 Database. 2 ADO.NET What is ADO.NET? ADO.NET is a part of the.NET Framework ADO.NET consists of a set of classes used.
1 11/15/05CS360 Windows Programming ADO.NET Continued.
COP2360 – C# Programming Chapter 14 – Nov 25, 2015.
HNDIT Rapid Application Development
Databases – Unit 3 & 4.  SQL is not restricted to a specific database, however in class we will be looking at the two major database programmes in use.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
Module 4 Introduction ADO.NET.
Module 2: Using ADO.NET to Access Data. Overview ADO.NET Architecture Creating an Application That Uses ADO.NET to Access Data Changing Database Records.
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.
ASP.NET Programming with C# and SQL Server First Edition
Data Access with ADO.NET
Accessing Databases using Ado.net
Introduction to Database Processing with ADO.NET
Introduction to Database Processing with ADO.NET
ADO.NET Framework.
Lecture 6 VB.Net SQL Server.
Tonga Institute of Higher Education
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Browser (Client Side) 瀏覽器 (客戶端)
Chapter 10 ADO.
Presentation transcript:

Lecture 11: Programmatic Database Access with ADO.NET

11-2 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Objectives “Programmatic database access typically involves executing SQL queries using classes from the language's framework. In.NET, the Active Data Objects (ADO) classes in the FCL are the primary means of database programming. ADO.NET is a vendor-neutral, object-oriented, SQL-based approach…” Architecture of ADO.NET Basic database access Application design Updating a database DataSets

11-3 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Part 1 Architecture of ADO.NET…

11-4 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Relational technology ADO.NET is designed to access relational databases Example: –Sales database with customers, orders, and products

11-5 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Architecture ADO.NET architecture based on data providers –data providers encapsulate DB-specific details Data Provider ADO.NET.NET Programmer DB

11-6 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Existing data providers.NET currently ships with 4 data providers: –one for Microsoft SQL Server –one for Oracle –one for older OLEDB technology (used for ADO, VB6) –one for older ODBC (Open Database Connectivity) technology More third-party providers are available… –Oracle's own provider: –DB2: –MySQL: –etc.

11-7 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET ADO.NET object model ADO.NET is an object-oriented approach Classes are spread across a number of FCL namespaces –some are provider-neutral, others are provider-specific SQL Server System.Data.Common System.Data System.Data.SqlClient System.Data.OleDb other DBs, e.g. MS Access provider-neutral ODBC (Open Database Connectivity) System.Data.Odbc

11-8 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Part 2 Basic database access…

11-9 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Overview of database access Three steps: 1.open connection to database 2.execute SQL to retrieve records / update DB 3.close connection

11-10 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET import System.Data.*; import System.Data.OleDb.*; String sConnection; sConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=Sales.mdb"; OleDbConnection dbConn; dbConn = new OleDbConnection(sConnection); dbConn.Open(); MessageBox.Show(dbConn.get_State().toString()); import System.Data.*; import System.Data.OleDb.*; String sConnection; sConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=Sales.mdb"; OleDbConnection dbConn; dbConn = new OleDbConnection(sConnection); dbConn.Open(); MessageBox.Show(dbConn.get_State().toString()); (1) Open connection Connections are opened based on connection string info –here we open a connection to a MS Access 2000 database –"Sales.mdb" must exist in same dir as.EXE (e.g. bin\Debug) connection

11-11 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Building connection strings Connection strings are vendor-specific Connection strings are not well-documented Where to turn for help? – –

11-12 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET (2) Retrieve records Retrieve records via SQL Select query –read-only access via DataReader & field names String sql, fn, ln; Customer c; sql = "Select * From Customers Order By LastName Asc, FirstName Asc;"; OleDbCommand dbCmd; OleDbDataReader dbReader; dbCmd = new OleDbCommand(sql, dbConn); dbReader = dbCmd.ExecuteReader(); while ( dbReader.Read() ) // retrieve records one-by-one… { fn = String.valueOf(dbReader.get_Item("FirstName")); ln = String.valueOf(dbReader.get_Item("LastName")); c = new Customer(fn, ln); this.listBox1.get_Items().Add(c); } String sql, fn, ln; Customer c; sql = "Select * From Customers Order By LastName Asc, FirstName Asc;"; OleDbCommand dbCmd; OleDbDataReader dbReader; dbCmd = new OleDbCommand(sql, dbConn); dbReader = dbCmd.ExecuteReader(); while ( dbReader.Read() ) // retrieve records one-by-one… { fn = String.valueOf(dbReader.get_Item("FirstName")); ln = String.valueOf(dbReader.get_Item("LastName")); c = new Customer(fn, ln); this.listBox1.get_Items().Add(c); } data reader record field name of data value in current record command connection

11-13 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET (3) Close connection Be sure to close reader and connection… –to flush pending updates (in general) –so others can access DB (connections are limited resources) dbReader.Close(); dbConn.Close(); dbReader.Close(); dbConn.Close();

11-14 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Part 3 Data-driven application design…

11-15 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Data Tier design Recall N-Tier design… GUI.exe DataAccess import System.Data.*; import System.Data.OleDb.*; public class DataAccess { private String sConnection; public DataAccess(String filename) { this.sConnection = String.Format("Provider=...;Data Source={0}{1}", System.AppDomain.get_CurrentDomain().get_BaseDirectory(), filename); } public java.util.ArrayList getCustomers() throws System.Exception {. } import System.Data.*; import System.Data.OleDb.*; public class DataAccess { private String sConnection; public DataAccess(String filename) { this.sConnection = String.Format("Provider=...;Data Source={0}{1}", System.AppDomain.get_CurrentDomain().get_BaseDirectory(), filename); } public java.util.ArrayList getCustomers() throws System.Exception {. }

11-16 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Guaranteed close? Ensure reader / DB closed via try-catch-finally pattern –and *note* that we want to catch.NET System.Exception objects, not Java java.lang.Exception objects… OleDbConnection dbConn = null; OleDbDataReader dbReader = null; try { dbConn = new OleDbConnection(…); dbConn.Open();. } catch(System.Exception ex) { System.Diagnostics.Debug.WriteLine("DB error: " + ex.get_Message()); throw new System.Exception("Data Error!", ex); } finally { // always executes whether we succeed or throw exception… if (dbReader != null) dbReader.Close(); if (dbConn != null) dbConn.Close(); } OleDbConnection dbConn = null; OleDbDataReader dbReader = null; try { dbConn = new OleDbConnection(…); dbConn.Open();. } catch(System.Exception ex) { System.Diagnostics.Debug.WriteLine("DB error: " + ex.get_Message()); throw new System.Exception("Data Error!", ex); } finally { // always executes whether we succeed or throw exception… if (dbReader != null) dbReader.Close(); if (dbConn != null) dbConn.Close(); }

11-17 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Part 4 Updating a database…

11-18 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Executing action queries Use action queries when you need to modify a DB –updates –inserts –deletes Execute action queries via ExecuteNonQuery method…

11-19 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Basic idea Open, execute, and close: String sConnection, sql; sConnection = "..."; sql = "..."; OleDbConnection dbConn; OleDbCommand dbCmd; dbConn = new OleDbConnection(sConnection); dbCmd = new OleDbCommand(sql, dbConn); int rows; dbConn.Open(); rows = dbCmd.ExecuteNonQuery(); // returns # of rows affected… dbConn.Close(); if (rows != 1) // sanity check to make sure it worked... throw new System.Exception("Query ran but failed to update DB?!"); String sConnection, sql; sConnection = "..."; sql = "..."; OleDbConnection dbConn; OleDbCommand dbCmd; dbConn = new OleDbConnection(sConnection); dbCmd = new OleDbCommand(sql, dbConn); int rows; dbConn.Open(); rows = dbCmd.ExecuteNonQuery(); // returns # of rows affected… dbConn.Close(); if (rows != 1) // sanity check to make sure it worked... throw new System.Exception("Query ran but failed to update DB?!");

11-20 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Dynamic SQL Most of the time you'll need to build SQL dynamically –i.e. based on input values from the user Example: –delete the selected customer… String fn, ln; Customer c; c = this.listBox1.get_SelectedItem(); fn = c.firstName; ln = c.lastName; sql = "..."; String fn, ln; Customer c; c = this.listBox1.get_SelectedItem(); fn = c.firstName; ln = c.lastName; sql = "...";

11-21 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Dynamic string building Dynamic SQL requires dynamic string building Example: –build dynamic SQL to delete selected customer… –don't forget the delimiters for strings & dates! String sql; sql = String.Format("Delete From Customers Where " + "FirstName='{0}' And LastName='{1}';", fn, ln); String sql; sql = String.Format("Delete From Customers Where " + "FirstName='{0}' And LastName='{1}';", fn, ln);

11-22 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Example Delete selected customer… private void listBox1_SelectedIndexChanged(…) { String fn, ln, sql; int rows; Customer c; c = (Customer) this.listBox1.get_SelectedItem(); if (c == null) return; // nothing selected… fn = c.firstName; ln = c.lastName; sql = String.Format("Delete From Customers Where " + "FirstName='{0}' And LastName='{1}';", fn, ln);. dbConn.Open(); rows = dbCmd.ExecuteNonQuery(); // delete! dbConn.Close(); if (rows != 1) throw new System.Exception("Query ran but failed to delete?!"); this.listBox1.get_Items().Remove(c); // update GUI! MessageBox.Show("Deleted!"); } private void listBox1_SelectedIndexChanged(…) { String fn, ln, sql; int rows; Customer c; c = (Customer) this.listBox1.get_SelectedItem(); if (c == null) return; // nothing selected… fn = c.firstName; ln = c.lastName; sql = String.Format("Delete From Customers Where " + "FirstName='{0}' And LastName='{1}';", fn, ln);. dbConn.Open(); rows = dbCmd.ExecuteNonQuery(); // delete! dbConn.Close(); if (rows != 1) throw new System.Exception("Query ran but failed to delete?!"); this.listBox1.get_Items().Remove(c); // update GUI! MessageBox.Show("Deleted!"); }

11-23 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Oops! Try to delete "O'Dahl, Kathie"… What happens?

11-24 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Escaping delimiters Most common DB programming mistake: –forgetting to escape delimiter characters… Solution? –just replace ' with 2 in a row, i.e. ' ' private void listBox1_SelectedIndexChanged(…) { String fn, ln, sql; int rows; Customer c; c = (Customer) this.listBox1.get_SelectedItem(); if (c == null) return; // nothing selected… fn = c.firstName; ln = c.lastName; fn = fn.Replace("'", "''"); ln = ln.Replace("'", "''"); sql = String.Format("Delete From Customers Where " + "FirstName='{0}' And LastName='{1}';", fn, ln); private void listBox1_SelectedIndexChanged(…) { String fn, ln, sql; int rows; Customer c; c = (Customer) this.listBox1.get_SelectedItem(); if (c == null) return; // nothing selected… fn = c.firstName; ln = c.lastName; fn = fn.Replace("'", "''"); ln = ln.Replace("'", "''"); sql = String.Format("Delete From Customers Where " + "FirstName='{0}' And LastName='{1}';", fn, ln);

11-25 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Part 5 DataSets…

11-26 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET DataSets DataSets are an in-memory data structure –easily filled with data from a database –easily passed around –easily displayed in a GUI app DataSet Name Price Stock Ants $ Birds $ Cats $ Dogs $ DB Command Connection DataAdapter DataSet mirrors the database –data forms a temporary table called "Table" within DataSet "Table"

11-27 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Filling a DataSet DataAdapter object is used to fill a DataSet… Example: –fill DataSet with all product data sql = "Select * From Products Order By Name Asc;";. DataSet ds; OleDbDataAdapter adapter; ds = new DataSet(); adapter = new OleDbDataAdapter(dbCmd); dbConn.Open(); adapter.Fill(ds); dbConn.Close(); sql = "Select * From Products Order By Name Asc;";. DataSet ds; OleDbDataAdapter adapter; ds = new DataSet(); adapter = new OleDbDataAdapter(dbCmd); dbConn.Open(); adapter.Fill(ds); dbConn.Close(); "Table" Name Price Stock Ants $ Birds $ Cats $ Dogs $

11-28 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET DataGrid display DataSet can be bound to DataGrid control for easy display –one line of code!. this.dataGrid1.SetDataBinding(ds, "Table");. this.dataGrid1.SetDataBinding(ds, "Table");

11-29 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET DataGrid is a powerful control By default, DataGrid is read/write –user can modify data –user can add rows –user can delete rows However, all changes are local to DataSet –to flush changes back to DB, reconnect and update…

11-30 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Flushing changes back to database Reconnect, and apply adapter's Update() method –use CommandBuilder object to generate necessary SQL for you // retrieve existing data set from grid… ds = (DataSet) this.dataGrid1.get_DataSource();. OleDbCommandBuilder cmdBuilder; cmdBuilder = new OleDbCommandBuilder(adapter); dbConn.Open(); adapter.Update(ds); // this will throw exception if update(s) conflict… dbConn.Close(); // retrieve existing data set from grid… ds = (DataSet) this.dataGrid1.get_DataSource();. OleDbCommandBuilder cmdBuilder; cmdBuilder = new OleDbCommandBuilder(adapter); dbConn.Open(); adapter.Update(ds); // this will throw exception if update(s) conflict… dbConn.Close();

11-31 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Summary Databases are a critical component of most business apps SQL is the standard programming language for databases Database programming is based on framework classes –in.NET, those classes are called ADO.NET –the more you know about SQL the better