 A database is an organized collection of data  A database management system (DBMS) provides mechanisms for storing, organizing, retrieving and modifying.

Slides:



Advertisements
Similar presentations
Chapter 10 Database Applications Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Advertisements

 Open the Paradise.exe file  Application displays records in the Books database  Allows the store manager to enter an author’s name (or part of a name)
 2003 Prentice Hall, Inc. All rights reserved. Chapter 22 – Database: SQL, MySQL, DBI and ADO.NET Outline 22.1 Introduction 22.2 Relational Database Model.
Chapter 18 - Data sources and datasets 1 Outline How to create a data source How to use a data source How to use Query Builder to build a simple query.
Damien Guard (BSc, MBCS) Guernsey Software Developer Forum Language Integrated Query:
Chapter 12: Using ADO.NET 2.0 Programming with Microsoft Visual Basic 2005, Third Edition.
Guide to Oracle10G1 Introduction To Forms Builder Chapter 5.
Introduction to Structured Query Language (SQL)
1 Pertemuan 09 Database Matakuliah: D0524 / Algoritma dan Pemrograman Komputer Tahun: 2005 Versi:
Concepts of Database Management Sixth Edition
CSCI 3328 Object Oriented Programming in C# Chapter 12: Databases and LINQ 1 Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
From VS C# 2010 Programming, John Allwork 1 VS2010 C# Programming - DB intro 1 Topics – Database Relational - linked tables SQL ADO.NET objects Referencing.
Some Basic Database Terminology
Databases and LINQ Visual Basic 2010 How to Program 1.
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
ASP.NET Programming with C# and SQL Server First Edition
 2008 Pearson Education, Inc. All rights reserved Database: SQL, MySQL, ADO.NET 2.0 and Java DB.
CHAPTER 7 Database: SQL, MySQL. Topics  Introduction  Relational Database Model  Relational Database Overview: Books.mdb Database  SQL (Structured.
A CCESSING D ATABASES WITH JDBC CH 24 C S 442: A DVANCED J AVA P ROGRAMMING.
10-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
DAY 14: ACCESS CHAPTER 1 Tazin Afrin October 03,
 SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size.
Advanced Visual Basic th Edition Chapter 3: Using SQL Server Databases (c) 2007 Pearson Education Inc. All rights reserved. You may modify and copy.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Twelve Access Databases and LINQ.
CHAPTER 8 Database: SQL, MySQL. Topics  Introduction  Relational Database Model  Relational Database Overview: Books.mdb Database  SQL (Structured.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Thirteen Working with Access Databases and LINQ.
Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Introduction to LINQ Lecture # 19 August Introduction How do you interrogate/manipulate data? What if you could do the work in a type-safe," string-free.
Database: SQL and MySQL
1 Databases November 15, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel, Deitel, and Goldberg. Published.
 2004 Prentice Hall, Inc. All rights reserved. 1 Segment – 6 Web Server & database.
Chapter Thirteen Working with Access Databases and LINQ Programming with Microsoft Visual Basic th Edition.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Chapter Thirteen Working with Access Databases and LINQ Programming with Microsoft Visual Basic th Edition.
CSCI 3327 Visual Basic Chapter 13: Databases and LINQ UTPA – Fall 2011.
Databases with LINQ. LINQ to SQL LINQ to SQL uses LINQ syntax to query databases. LINQ to SQL classes are automatically generated by the IDE’s LINQ to.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
1 Chapter 20 – Data sources and datasets Outline How to create a data source How to use a data source How to use Query Builder to build a simple query.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved. 2 Revised by Dr. T. Tran for CSI3140.
Chapter Fourteen Access Databases and SQL Programming with Microsoft Visual Basic th Edition.
A CCESSING D ATABASES WITH JDBC CH 24 C S 442: A DVANCED J AVA P ROGRAMMING.
 2008 Pearson Education, Inc. All rights reserved Database: SQL, MySQL, ADO.NET 2.0 and Java DB.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 22 - SQL, MySQL, DBI and ADO Outline 22.1 Introduction 22.2 Relational Database Model 22.3 Relational.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 25 I’m Suffering from Information Overload.
1 Chapter 10 – Database Management 10.1 An Introduction to Databases 10.2 Editing and Designing Databases.
Chapter 24 I’m Suffering from Information Overload (Access Databases) Clearly Visual Basic: Programming with Visual Basic nd Edition.
 2009 Pearson Education, Inc. All rights reserved Databases and LINQ to SQL.
CSCI 3328 Object Oriented Programming in C# Chapter 12: Databases and LINQ – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg,
Damien Guard (BSc, MBCS) Guernsey Software Developer Forum Language Integrated Query:
Database: SQL, MySQL, LINQ and Java DB © by Pearson Education, Inc. All Rights Reserved.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
CSCI 3327 Visual Basic Chapter 13: Databases and LINQ UTPA – Fall 2011.
Programming with Microsoft Visual Basic 2012 Chapter 14: Access Databases and SQL.
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
Database, SQL and ADO.NET
Microsoft Visual Basic 2010: Reloaded Fourth Edition
Visual Basic 2010 How to Program
 2012 Pearson Education, Inc. All rights reserved.
Language Integrated Query: (LINQ) An introduction
JDBC.
Databases Intro (from Deitel)
The University of Texas – Pan American
CIS16 Application Programming with Visual Basic
Chapter 22 - SQL, MySQL, DBI and ADO
CIS16 Application Programming with Visual Basic
Database Applications
Presentation transcript:

 A database is an organized collection of data  A database management system (DBMS) provides mechanisms for storing, organizing, retrieving and modifying data for many users  SQL is the international standard language used with relational databases to perform queries and to manipulate data  Popular relational database management systems (RDBMSs) ◦ Microsoft SQL Server ◦ Oracle ◦ Sybase ◦ IBM DB2 ◦ Informix ◦ PostgreSQL ◦ MySQL Databases

 A relational database is a logical representation of data that allows the data to be accessed without consideration of its physical structure  A relational database stores data in tables  Tables are composed of rows, and rows are composed of columns in which values are stored  Primary key —a column (or group of columns) with a unique value that cannot be duplicated in other rows

 The database consists of three tables: ◦ Authors ◦ AuthorISBN ◦ Titles  The Authors table consists of three columns that maintain each author’s unique ID number, first name and last name  The AuthorISBN table consists of two columns that maintain each ISBN and the corresponding author’s ID number  The Titles table consists of four columns that stand for the ISBN, the title, the edition number and the copyright year  Foreign key —a column in a table that matches the primary key column in another table.  Helps maintain the Rule of Referential Integrity—every foreign-key value must appear as another table’s primary-key value  There is a one-to-many relationship between a primary key and a corresponding foreign key Books Database

 Entity-relationship (ER) diagram for the books database ◦ Shows the database tables and the relationships among them ◦ The names in italic are primary keys  A table’s primary key uniquely identifies each row in the table  Every row must have a primary-key value, and that value must be unique in the table ◦ This is known as the Rule of Entity Integrity Books Database (cont.)

SQL (basics)

 A SQL query “selects” rows and columns from one or more tables in a database.  The basic form of a SELECT query is  SELECT * FROM tableName  in which the asterisk (*) wildcard character indicates that all columns from the tableName table should be retrieved.  To retrieve all the data in the Authors table, use  SELECT * FROM Authors  To retrieve only specific columns, replace the asterisk (*) with a comma-separated list of the column names, e.g.,  SELECT AuthorID, LastName FROM Authors SQL SELECT

 In most cases, only rows that satisfy selection criteria are selected  SQL uses the optional WHERE clause in a query to specify the selection criteria for the query  The basic form of a query with selection criteria is  SELECT columnName1, columnName2, … FROM tableName WHERE criteria  To select the Title, EditionNumber and Copyright columns from table Titles for which the Copyright date is greater than 2005, use the query  SELECT Title, EditionNumber, Copyright FROM Titles WHERE Copyright > '2005'  Strings in SQL are delimited by single (') rather than double (") quotes  The WHERE clause criteria can contain the operators, =, =, <> and LIKE WHERE Close

 Operator LIKE is used for pattern matching with wildcard characters percent (%) and underscore (_)  A pattern that contains a percent character (%) searches for strings that have zero or more characters at the percent character’s position in the pattern  For example, the next query locates the rows of all the authors whose last name starts with the letter D:  SELECT AuthorID, FirstName, LastName FROM Authors WHERE LastName LIKE 'D%' Operator LIKE

Wildcard characterDescriptionExample %Any string of zero or more characters.WHERE title LIKE '%computer%' finds all book titles with the word 'computer' anywhere in the book title. _ (underscore)Any single character.WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on). [ ]Any single character within the specified range ([a-f]) or set ([abcdef]). WHERE au_lname LIKE '[C-P]arsen' finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation. [^]Any single character not within the specified range ([^a-f]) or set ([^abcdef]). WHERE au_lname LIKE 'de[^l]%' all author last names starting with de and where the following letter is not l. Other Patterns

 The rows in the result of a query can be sorted into ascending or descending order by using the optional ORDER BY clause.  The basic form of a query with an ORDER BY clause is  SELECT columnName1, columnName2, … FROM tableName ORDER BY column ASC SELECT columnName1, columnName2, … FROM tableName ORDER BY column DESC ◦ ASC specifies ascending order (lowest to highest) ◦ DESC specifies descending order (highest to lowest) ◦ column specifies the column on which the sort is based.  To obtain the list of authors in ascending order by last name (), use the query  SELECT AuthorID, FirstName, LastName FROM Authors ORDER BY LastName ASC  To obtain the same list of authors in descending order by last name (), use the query  SELECT AuthorID, FirstName, LastName FROM Authors ORDER BY LastName DESC  Multiple columns can be used for sorting with an ORDER BY clause of the form  ORDER BY column1 sortingOrder, column2 sortingOrder, … ◦ sortingOrder is either ASC or DESC.  Sort all the rows in ascending order by last name, then by first name.  SELECT AuthorID, FirstName, LastName FROM Authors ORDER BY LastName, FirstName ORDER BY Clause

 The WHERE and ORDER BY clauses can be combined in one query, as in  SELECT ISBN, Title, EditionNumber, Copyright FROM Titles WHERE Title LIKE '%How to Program' ORDER BY Title ASC  which returns the ISBN, Title, EditionNumber and Copyright of each book in the Titles table that has a Title ending with "How to Program" and sorts them in ascending order by Title ORDER BY Clause cont

SqlConnection con = new SqlConnection(...); con.Open(); SqlCommand cmd = new * FROM Customers WHERE c.Region con ); "US"); DataReader dr = cmd.ExecuteReader(); while (dr.Read()) { string name = dr.GetString(dr.GetOrdinal("Name")); string phone = dr.GetString(dr.GetOrdinal("Phone")); DateTime date = dr.GetDateTime(3); } dr.Close(); con.Close();

var myCustomers = from c in customers where c.Region == "US" select c; var goodCusts = (from c in db.Customers where c.PostCode.StartsWith("GY") orderby c.Sales descending select c).Skip(10).Take(10);

 Unified data access  Single syntax to learn and remember  Strongly typed  Catch errors during compilation  IntelliSense help  Prompt for syntax and attributes  Bindable result sets

OthersC#VB.NET.NET Language Integrated Query (LINQ) LINQ to SQL LINQ to Objects LINQ to XML LINQ to Datasets LINQ to Entities LINQ data source providers ADO.NET support for LINQ

int[] nums = new int[] {0,4,2,6,3,8,3,1}; double average = nums.Take(6).Average(); var above = from n in nums where n > average select n;

 Query any IEnumerable source Includes arrays, List, Dictionary...  Many useful operators available Sum, Max, Min, Distinct, Intersect, Union  Expose your own data with IEnumerable or IQueryable  Create operators using extension methods

 Object-relational mapping  Records become strongly-typed objects  Data context is the controller mechanism  Facilitates update, delete & insert  Translates LINQ queries behind the scenes  Type, parameter and injection safe  Map tables & fields to classes & properties  Generates partial classes with attributes  Each record becomes an object  Data context represents the database  Utilize tables, views or stored procedures

 The LINQ to SQL class uses LINQ syntax to query databases, the same used to query arrays and collections and files  LINQ to SQL classes are automatically generated by the IDE’s LINQ to SQL Designer.  The IDE creates a class for each table, with a property for each column in the table  A cache is a temporary store created for fast access to data  LINQ to SQL caches all row objects that it creates, making interacting with the database more efficient  This can reduce round trips to the database

 LINQ queries on an Iueryable interface (which inherits from the IEnumerable interface) are processed together as a single SQL statement  If each query operator were handled separately, multiple round trips to the database would be needed  All LINQ to SQL queries occur via a DataContext class controls the flow of data between the program and the database  a DataContext has properties for each table in the DB, which can be used as data sources in LINQ queries  When cached objects have been changed, these changes are saved using the DataContext’s SubmitChanges method

 Create a new Windows Form s Application named DisplayTable  Change the name of the source file to DisplayTableForm.cs.

33  View->Other Windows->Database Explorer->Data Connections->  Add Connections  If the Choose Data Source dialog appears, select Microsoft SQL Server Database File from the Data source: ListBox.  Click Continue to open the Add Connection dialog.  Click Browse… and choose Books.mdf. SQL Server Express allows only one application at a time to access a database file. Ensure that no other program is using the database file before you attempt to add it to the project.

SQL SELECT via VS C#

 Right click the project in the Solution Explorer and select Add > New Item… Select LINQ to SQL classes, name the new item Books.dbml and click the Add button

 The Database Explorer window allows you navigate the structure of databases  Drag the Authors, Titl e s and AuthorISBN tables onto the Object Relational Designer and select Yes. Error-Prevention Tip 18.2 Be sure to save the file in the Object Relational Designer before trying to use the LINQ to SQL classes in code. The IDE does not generate the classes until you save the file

Creates BooksDataContext

Creating Data Bindings  Select Data > Add New Data Source… to display the Data Source Configuration Wizard.  In the dialog, select Object and click Next >  Expand the tree view and select DisplayTable > DisplayTable > Author.  Click Next > then Finish. The Authors table in the database is now a data source that can be used by the bindings.

 Expand the tree view and select DisplayTable > DisplayTable > Author.  Click Next > then Finish. The Authors table in the database is now a data source that can be used by the bindings.

44  Data > Show Data Sources  Open the DisplayTableForm in Design view.  Click the Author node in the Data Sources window—it should change to a drop-down list. Ensure that the DataGridView option is selected.

45  Drag the Author node from the Data Sources window to the DisplayTableForm.  The IDE creates a DataGridView with the correct column names and a BindingNavigator.

46  The BindingNavigator contains Button s for moving between entries, adding entries, deleting entries and saving changes to the database.  A BindingSource transfers data between the data source and the data-bound controls on the Form.

Property Dock is Fill

 Create the Form’s Load handler by double clicking the title bar in Design view 21 private void DisplayTableForm_Load(object sender,EventArgs e) 22 { 23 // use LINQ to order the data for display 24 authorBindingSource.DataSource = 25 from author in database.Authors 26 orderby author.AuthorID 27 select author; 28 }

Fig | Component tray holds nonvisual components in Design view. Component tray

51 DisplayTable Form.cs ( 1 of 3 ) Figure shows the code needed to move data back and forth between the database and GUI. Fig | Component tray holds nonvisual components in Design view. (Part 1 of 3. )

DisplayTable Form.cs ( 2 of 3 ) A DataContext object allows the application to interact with the database. The BindingSource ’s DataSource property is set to the results of a LINQ query. LINQ is used to extract data from the Authors table in the database. Fig | Component tray holds nonvisual components in Design view. (Part 2 of 3. )

53 DisplayTable Form.cs ( 3 of 3 ) First, all controls on the form are validated. EndEdit forces any pending changes to be saved. SubmitChanges stores any changes to the database. Fig | Component tray holds nonvisual components in Design view. (Part 3 of 3. )

// click event handler for the Save Button in the // BindingNavigator saves the changes made to the data private void authorBindingNavigatorSaveItem_Click( object sender, EventArgs e) { Validate(); // validate input fields authorBindingSource.EndEdit(); // indicate edits are complete database.SubmitChanges(); // write changes to database file } Saving data Set Enabled to true

Use the Properties window to set the save button’s Enabled property to True. Saving the data back to the database is a three-step process: First, all controls on the form are validated. EndEdit forces any pending changes to be saved. SubmitChanges stores any changes to the database. 35 Validate (); // validate input fields 36 authorBindingSource. EndEdit (); // indicate edits are complete 37 database. SubmitChanges (); // write changes to database file

 To persist changes between program executions, select the database in the Solution Explorer and set the Copy to Output Directory property to Copy if newer.

Run the application to verify that it works.

 Create a new Windows Forms Application named DisplayQueryResult.  Rename its C# file to DisplayQueryResultForm.cs.  Add the Books database to the project and generate the LINQ to SQL classes.