C# Programming in Depth Prof. Dr. Bertrand Meyer March 2007 – May 2007 Chair of Software Engineering Lecture 10: Database Lisa (Ling) Liu.

Slides:



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

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.
Chapter 12: ADO.NET and ASP.NET Programming with Microsoft Visual Basic.NET, Second Edition.
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.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
VB.NET Database Access ISYS 812. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
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.
From VS C# 2010 Programming, John Allwork 1 VS2010 C# Programming - DB intro 1 Topics – Database Relational - linked tables SQL ADO.NET objects Referencing.
Databases and LINQ Visual Basic 2010 How to Program 1.
Programming with Visual Basic.NET An Object-Oriented Approach  Chapter 8 Introduction to Database Processing.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
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.
Intro to C#.net and EF Ilan Shimshoni. The Three Faces of ADO.NET The connected layer – Directly connecting to the DB The disconnected layer – Using datasets.
FEN Data connection DataReader DataSet Bonus info: Concurrency and Database Transactions Embedded SQL.
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.
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.
1 11/3/05CS360 Windows Programming Databases and Data Representation.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Databases and Data Access  Introduction to ADO.NET  ADO.NET objects  ADP.NET namespaces  Differences between ADO and ADO.NET.
CHAPTER EIGHT Accessing Data Processing Databases.
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.
CHAPTER EIGHT Accessing Data Processing Databases.
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:
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.
 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 Data Classes- DataView DataGridView Control. Objectives 2  Data Class  DataAdapter  DataReader  DataSet  DataTable  DataView  DataGridView Control.
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.
Mauricio Featherman, Ph.D. Washington St. University
Introduction to ADO.Net and VS Database Tools and Data Binding ISYS 350.
DataSet Your Database student test score Database Connection Your program needs to establish a connection to the database. Click on “Add New Data Source.”
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.
HNDIT Rapid Application Development
ADO.NET FUNDAMENTALS BEGINNING ASP.NET 3.5 IN C#.
C# .NET Software Development
ADO.NET Objects Data Adapters Dr. Ron Eaglin. Agenda Builds on Information in Part I Should have working knowledge of creating a database connection Continuation.
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
Common SQL keywords. Building and using CASE Tools Data Base with Microsoft SQL-Server and C#
ASP.NET Programming with C# and SQL Server First Edition
Introduction to 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)
Chapter 10 ADO.
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
Introduction to ADO.Net and Visual Studio Database Tools.
Presentation transcript:

C# Programming in Depth Prof. Dr. Bertrand Meyer March 2007 – May 2007 Chair of Software Engineering Lecture 10: Database Lisa (Ling) Liu

C# programming lecture 10: Database 2 Database and Data Representation  Database Management System (DBMS):  provides efficient, convenient, and safe multi-user storage of persistent data  provides access to massive amounts of persistent data  provides a programming interface that allows a user or program to  create new database and specify their struture  query and modify the data  Dominant approach: relational database and SQL

C# programming lecture 10: Database 3 Database and Data Representation EmployeeIDTitleManagerIDVacationHours 1Production Technician Marketing Assistant 642 3Engineering Manager 122 4Senior Tool Designer 348 Int32StringInt32Int16 Employee

C# programming lecture 10: Database 4 Database and Data Representation  A “relation” is a table of data  The columns are known as “attributes”  The row are called “tuples”  It is allowable for some values to be missing  We can add, remove, or update tuples  Each attribute has an underlying domain, or data type

C# programming lecture 10: Database 5 SQL Database  We will generally refer to the relations, attributes, and tuples as tables, columns, and rows  The structure of a table is referred to as its schema

C# programming lecture 10: Database 6 SQL Database EmployeeIDTitleManagerIDVacationHours 1Production Technician Marketing Assistant 642 3Engineering Manager 122 4Senior Tool Designer 348 Primary key: no two rows can have the same EmployeeID. EmployeeID cannot be null. Employee Primary key

 Assume that we want to add data about employees’ salary  Assume an employee’s salary is changeable, we need to add following two columns.  RateChangeDate  Rate  We can’t add additional columns for the same employee without violating the primary key constraint. So we use another table.

EmployeeIDTitleManagerIDVacationHours 1PT1621 2MA642 3EM122 4STD348 Employee EmployeeIDRateChangeDateRate EmployeePayHistory EmployeeID establishs a relationship between the tables.

EmployeeIDTitleManagerIDVacationHours 1PT1621 2MA642 3EM122 4STD348 Employee EmployeeIDRateChangeDateRate EmployeePayHistory We say that there is a “foreign key constraints” between the tables. Relation one-to-many parent/child The column referenced in the parent table must be a primary key Every value in the foreign column must actually appear in the parent table. Foreign key

C# programming lecture 10: Database 10 Simple SQL Queries  SELECT SELECE * what columns to output FROM Employee what tables are involved WHERE VacationHours > 20 what rows are of interest

EmployeeIDTitleManagerIDVacationHours 1PT1621 2MA642 3EM122 4STD348 Employee EmployeeIDManagerID SELECT EmployeeID, ManagerID FROM Employee WHERE VacationHours > 20

C# programming lecture 10: Database 12 How to interact with data stores?  ADO.NET a set of namespaces defined on.NET platform that understand how to interact with data stores.  native support for SQL Server and Oracle  support for other databases via older OleDB technology  requires a knowledge of SQL

C# programming lecture 10: Database 13 ADO.NET-centric Namespaces  Core namespaces:  general: System.Data  SQL Server: System.Data.SqlClient  Oracle: System.Data.OracleClient  OleDB: System.Data.OleDb

C# programming lecture 10: Database 14 Two manners of accessing database  Connected manner  explicitly connected to and disconnected from the underlying data store  Disconnected manner  using DataSet – a local copy of external data to interact with data stores

C# programming lecture 10: Database 15 Data Providers Client Assembly.NET Platform Data Provider Transaction Connection Object Parameter Collection Connection Object DataReader Object DataAdapter Object Select Command Insert Command Update Command Delete Command Database ADO.NET providers provide access to a given DBMS.

C# programming lecture 10: Database 16 Overview of database access  General steps: – open connection to database – execute SQL to retrieve records / update DB – close connection

C# programming lecture 10: Database 17 Database Access ( Connect Manner ) Five steps: 1. Allocate, configure, and open your connection object 2. Allocate and configure a command object 3. Acquire DataReader object 4. Process each record using DataReader object 5. Close connection

C# programming lecture 10: Database 18 Step 1: open connection  Connections are opened based on connection string info  here we open a connection to a SQL Server database  “AdvertureWorks" database must be installed on the local machine. using System.Data; using System.Data.SqlClient;... SqlConnection cn = new SqlConnection(); cn.ConnectionString = " server=(local);database=AdventureWorks;integrated security=true "; cn.Open(); MessageBox.Show( cn.State.ToString() ); connection

C# programming lecture 10: Database 19 Building connection strings  Connection strings are vendor-specific, not well- documented  Where to turn for help?  

C# programming lecture 10: Database 20 Step 2-4: retrieve records  Retrieve records via SQL Select query  read-only access by database field names string strSQL = "SELECT * FROM HumanResources.Employee"; SqlCommand myCommand = new SqlCommand(strSQL, cn); SqlDataReader myDataReader; myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection); while (myDataReader.Read()) { Console.WriteLine("EmployeeID: {0}, Title: {1}, ManagerID: {2}, VacationHours: {3}", myDataReader["EmployeeID"].ToString().Trim(), myDataReader["Title"].ToString().Trim(), myDataReader["ManagerID"].ToString().Trim(), myDataReader["VacationHours"].ToString().Trim()); } data reader record

C# programming lecture 10: Database 21 Step 5: close connection  Be sure to close connection…  to flush pending updates  so others can access DB (connections are limited resources) cn.Close();

C# programming lecture 10: Database 22 Guaranteed close? IDbConnection dbConn = null; try { cn.Open();. } catch(Exception ex) { System.Diagnostics.EventLog.WriteEntry("MyApp", ex.Message); System.Diagnostics.EventLog.WriteEntry("MyApp", ex.StackTrace); throw ex; } finally { if ((cn != null) && (cn.State != ConnectionState.Closed)) cn.Close(); }

C# programming lecture 10: Database 23 Updating a database To update database, execute an SQL Action query Example:  delete employee by their id number string sql = string.Format("DELETE FROM Employee WHERE EmployeeID = '{0}'", employeeID); SqlCommand cmd = new SqlCommand(sql, cn); try { cmd.ExecuteNonQuery(); } catch { Console.WriteLine("Sorry! That employ cannot be deleted."); }

C# programming lecture 10: Database 24 Example of action queries Insert, update and delete: Insert Into Customers(CID, FirstName, LastName, CreditLimit, Balance) Values(118, 'Jia', 'Zhang', , 0.0); Update Customers Set CreditLimit = , Balance = 0.0 Where LastName = 'Gates' and FirstName = 'Bill'; Delete From Customers Where CID = 666;

C# programming lecture 10: Database 25 Database Access (Disconnect Manner) SQL Database SQL Server SqlDataAdapter SqlCommand − “SELECT * FROM Table1” − Sql Connection Fill (myDataSet, “myTable”) DataSet Client Application Forms

C# programming lecture 10: Database 26 DataSet  DataSets are an in-memory, read-write data structure  easily filled with data from a database  easily displayed in a GUI app DataSet DataTablesCollection DataRelationCollection PropertyCollection

C# programming lecture 10: Database 27 DataAdapter  make use of DataSet objects to move data between client and data store.  is used to fill DataSet with DataTable objects  send modified DataTables back to the database for processing  take care of connection, hence client don’t need to explicitly open and close the connection with DBMS

C# programming lecture 10: Database 28 Steps 1.construct data adapter with a valid connection or connection string and a command object 2.fill DataSet using the internal command within the data adapter 3.operate on the DataSet 4.using data adapter to update data store with the DataSet

C# programming lecture 10: Database 29 Example Retrieve product info and display in a DataGrid: string sql = "SELECT * FROM Employee"; SqlCommand myCmd = new SqlCommand(sql, cn); SqlDataAdapter myAdapter = new SqlDataAdapter(myCmd); DataSet myDS = new DataSet("HumanResources"); myAdapter.Fill(myDS, "Employee"); PrintDataSet(myDS);

C# programming lecture 10: Database 30 Flushing changes back to database sql = string.Format("INSERT INTO Employee" + "(Title, ManagerID, VacationHours) VALUES" + "('{0}', '{1}', '{2}')", title, managerID, vacationHours); SqlCommand insertCmd = new SqlCommand(sql, cn); myAdapter.InsertCommand = insertCmd; //Update Employee table with new row DataRow newEmployee = myDS.Tables["Employee"].NewRow(); newEmployee["Title"] = title; newEmployee["ManagerID"] = managerID; newEmployee["VacationHours"] = vacationHours; myDS.Tables["Employee"].Rows.Add(newEmployee); myAdapter.Update(myDS.Tables["Employee"]);

C# programming lecture 10: Database 31 Untyped DataSets  Collection of tables  Tables are collections of columns and rows  Rows hold the data  Filling tables does not create relations between them carName = myDS.Tables[“Inventory"].Rows[0][“PetName”]  To use relations between tables in memory, we must write code that builds the relations

C# programming lecture 10: Database 32 Typed DataSets  A class derived from DataSet  Incorporates the schemas for the tables it contains  Has properties and methods that allow access to tables and columns by name  Extends DataSet, DataTable, DataRow to provide custom classes  Table, column, and method are known by names, reducing coding time and erros carName = myDs.Inventory[0].PetName;

C# programming lecture 10: Database 33 Generating a typed DataSet 1.Right-click project 2.Add | Add new item.. | Data Set 3.Select a name 4.Find the tables of interest in the Server Explorer and dray them onto the design surface 5.Drag relations onto the child tables and verify the settings 6.Save  A file with extension.xsd that represents the tables and schemas  A class derived from DataSet in a.cs file

C# programming lecture 10: Database 34 Questions