Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: " A database is an organized collection of data  A database management system (DBMS) provides mechanisms for storing, organizing, retrieving and modifying."— Presentation transcript:

1

2  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

3  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

4

5  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

6

7

8

9

10

11

12  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.)

13

14

15 SQL (basics)

16  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

17  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

18  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

19 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

20  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

21  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

22 SqlConnection con = new SqlConnection(...); con.Open(); SqlCommand cmd = new SqlCommand( @"SELECT * FROM Customers WHERE c.Region = @Region", con ); cmd.Parameters.AddWithValue("@Region", "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();

23 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);

24  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

25 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

26 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;

27  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

28  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

29  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

30  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

31

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

33 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.

34

35

36

37 SQL SELECT via VS C#

38  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

39  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

40

41 Creates BooksDataContext

42 18.5.2 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.

43  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 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 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 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.

47 Property Dock is Fill

48  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 }

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

50

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

52 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. 18.18 | Component tray holds nonvisual components in Design view. (Part 2 of 3. )

53 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. 18.18 | Component tray holds nonvisual components in Design view. (Part 3 of 3. )

54 // 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

55 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

56  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.

57 Run the application to verify that it works.

58  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.


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

Similar presentations


Ads by Google