Overheads Chap. 4
Transcription
Overheads Chap. 4
4-1 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Chapter McGraw-Hill 4 Windows Database Using Related Tables This chapter examines techniques for establishing relationships among tables and extracting data from the tables. Objectives (1 of 2) Explain the types of table relationships master-detail records Display a field from a second table using a lookup Create a search using a parameterized query and write a filter to retrieve specific data Assign data values to unbound controls Display McGraw-Hill 4-3 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 1 Objectives (2 of 2) Retrieve and display the parent row for a selected child row Retrieve and display an array of child rows for a selected parent row Create an application that displays from a many-to-many relationship Select the correct locations for handling and formatting data in a multitier application McGraw-Hill 4-4 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Data Relationships Data stored in multiple related tables table Î parent or master Second table Î child or detail The primary key of one table is included as a field in a related table to link the two tables The key included in the related table is called a foreign key Primary McGraw-Hill 4-5 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. One-to-Many Relationships Most common type of relationship record in the parent table relates to one or more records in the child table One Examples McGraw-Hill include: Customer with multiple order Student with multiple courses 4-6 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 2 Many-to-Many Relationships Example: One author can write many books; one book can have many authors SQL Server and Access require a junction table to join two tables The junction table’s primary key consists of the foreign keys from both tables McGraw-Hill 4-7 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. One-to-One Relationships Least common relationship record in the parent matches one record in the child table Usually the two table could be combined but may be kept separate for security reasons or the child table contains short-term information One McGraw-Hill 4-8 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Constraints A unique constraint specifies that no duplicate entries are allowed in a column Foreign-key constraints ensure that parent and child tables remain synchronized when records are deleted or changed The Thereferential referentialintegrity integrityconcept concept isisenforced enforcedby bythe theDBMS DBMSusing using foreign key constraints to ensure foreign key constraints to ensurethat that changes changesand anddeletions deletionsininone onetable table are made to all affected tables. are made to all affected tables. McGraw-Hill 4-9 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 3 Creating a Dataset with More Than One Table The DataSet object can hold more than one table and the relationships between the tables To generate a DataSet with multiple tables, check the boxes for both tables in the Data Source Configuration Wizard McGraw-Hill 4-10 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Viewing or Setting a Relationship A DataRelation object describes the relationship between the tables Use the XML schema (.xsd) file for the dataset to create the relationship McGraw-Hill 4-11 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Specifying the Parent, Child, and Foreign Key When adding a relationship to a DataSet’s schema, it’s important to get the parent/child relationship right Determine which table is the “one side” and which is the “many side” in a one-to-many relationship The “one side” should always be the parent and the “many side” should be the child McGraw-Hill 4-12 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 4 Queries and Filters A parameterized query creates a new DataSet that holds the selected records A filter selects records from an existing DataSet Use McGraw-Hill a filter when you already have a complete DataSet 4-13 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Using a Parameterized Query SQL statement that retrieves selected record(s) based on a value that the user enters at run time The value supplied by the user is called a parameter which is the basis for the term parameterized query McGraw-Hill 4-14 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Selecting Specific Records If a DataSet is to contain only selected record(s), the SQL SELECT used by the TableAdapter can be modified Use a WHERE clause in an SQL query to specify which records to select, called the criteria SELECT SELECT Title, Title, Author, Author, ISBN ISBN FROM FROM Books Books WHERE WHERE Title Title == 'Romeo 'Romeo and and Juliette' Juliette' SELECT SELECT Name, Name, AmountDue AmountDue FROM FROM OverdueAccounts OverdueAccounts WHERE WHERE AmountDue AmountDue >> 100 100 SELECT SELECT emp_id, emp_id, lname, lname, fname fname FROM FROM employee employee WHERE WHERE lname lname == 'Jones' 'Jones' McGraw-Hill 4-15 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 5 Query Builder Enter Enterthe theparameter parameterininthe the Filter FilterBox Boxand andthe theWhere Where clause clauseisiscreated. created. The Thegrid gridfills fillswith withthe the selected selectedrecords records McGraw-Hill 4-16 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Writing a Filter Rules for creating a filter are the same as for a WHERE clause of an SQL statement Specify the field, a comparison operator (usually the equals sign), and the value to match ""LastName LastName == Jones Jones"" ""SalesAmount SalesAmount == 1000 1000"" ""Quantity Quantity >> 00"" Use single quotes to enclose the value to match when a string contains spaces ""Title Title McGraw-Hill 4-17 == 'A'A Great Great Book Book'"'" © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Useful Comparison Operators Operator Meaning Examples = Equal to "Subject = 'Business'" "Subject = '" & subjectTextBox.Text & "'" > Greater than "Sales > 1000" "Sales > " & salesTextBox.Text < Less than "Sales < 1000" "Sales < " & salesTextBox.Text Like Pattern match "Subject Like ('B%')" (SQL Server) "Subject Like 'B*'" (Access) McGraw-Hill 4-18 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 6 Binding a List at Run Time List usually appears empty until a selection is made the control in code rather than at design time When the DataSource is set, the list fills with the data from the BindingSource Bind ' 'Bind Bind the the list list box box with with the the filtered filtered data. data. With With employeeListBox employeeListBox .DataSource .DataSource == BindingSource1 BindingSource1 .DisplayMember Name"" .DisplayMember == ""Name End End With With McGraw-Hill 4-19 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Completed Filter Exercise User selects a job description from the combo box corresponding job_id is used to filter the data All matching records display in the list box The McGraw-Hill 4-20 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Unbound Data Fields Controls that do not have data bindings are called unbound controls Assign a field of data at run time, in code Must reference individual database fields from the dataset McGraw-Hill 4-21 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 7 Referring to Records and Fields Actual data values are held in DataRow objects Table object in a DataSet has a DataRows collection made up of DataRow objects The data values are held in the DataRow.Items collection Each McGraw-Hill 4-22 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Referring to Fields Reference the DataRow Items collection firstNameString firstNameString == employeeDataRow.Item(1).ToString employeeDataRow.Item(1).ToString oror firstNameString firstNameString == employeeDataRow.Item(“fname”).ToString employeeDataRow.Item(“fname”).ToString or or firstNameString firstNameString == employeeDataRow!fname.ToString employeeDataRow!fname.ToString McGraw-Hill 4-23 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Working With Parent and Child Records DataRelation objects relate parent and child records Use the DataRelation to retrieve the parent of a child record or find an array of matching child row(s) for a given parent Remember the rule—the one side of a one-to-many relation is the parent; the many side is the child McGraw-Hill 4-24 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 8 Retrieving a Related Parent Row From the selected employee name, the program retrieves the correct employee DataRow and the matching Jobs parent DataRow to display the job description McGraw-Hill 4-25 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Find the Parent Row for a Child Record Find the row in the child table (employee) that matches the combo box selection Dim Dim employeeDataRow employeeDataRow As As DataRow DataRow employeeIDString employeeIDString == employeeComboBox.SelectedValue.ToString employeeComboBox.SelectedValue.ToString employeeDataRow employeeDataRow == PubsDataSet.employee.FindByemp_id( PubsDataSet.employee.FindByemp_id( __ employeeIDString) employeeIDString) Get the parent row from the parent (jobs) table Dim Dim jobDataRow jobDataRow As As DataRow DataRow jobDataRow jobDataRow == employeeDataRow("EmployeeToJobsRelation") employeeDataRow("EmployeeToJobsRelation") Retrieve specific field from the parent data row jobTitleTextBox.Text jobTitleTextBox.Text == jobDataRow!job_desc.ToString jobDataRow!job_desc.ToString McGraw-Hill 4-26 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Retrieving Related Child Rows Retrieve an array of related child rows The GetChildRows method is similar to retrieving a related parent row The difference is that the GetChildRows method returns an array of rows instead of a single row The TheComplete CompleteFind FindParent ParentProgram Program––p. p.170 170 The TheComplete CompleteFind FindChild ChildProgram Program––p. p.171-172 171-172 McGraw-Hill 4-27 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 9 Many-to-Many Relationships In an M:N relationship, two 1:M relationships must be set up. The junction table is the child table in each of the two 1:M relationships McGraw-Hill 4-28 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. Multitier Considerations Be sure to think through the goals of OOP presentation tier should provide only the user interface All user input and output formatting belongs in the form Data retrieval and any processing should be handled in other classes The user interface should be able to completely change without modifying the other classes Filtering or data retrieval method changes should not affect the interface The McGraw-Hill 4-29 © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 10