Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 10, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 10 Working With Databases.

Similar presentations


Presentation on theme: "Chapter 10, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 10 Working With Databases."— Presentation transcript:

1 Chapter 10, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 10 Working With Databases

2 Chapter 10, Slide 2Starting Out with Visual Basic 3 rd Edition Chapter 10 Introduction

3 Chapter 10, Slide 3Starting Out with Visual Basic 3 rd Edition Chapter 10 Topics Basic database terminology Fundamental database concepts Use ADO.NET to access databases Display, sort, and update database data Use the DataGridView control

4 Chapter 10, Slide 4Starting Out with Visual Basic 3 rd Edition Section 10.1 What Is a Database? A Database is a Collection of Data Organized in Tables, Rows, and Columns

5 Chapter 10, Slide 5Starting Out with Visual Basic 3 rd Edition Terminology Database: a collection of interrelated tables Table: a logical grouping of related data A category of people, places, or things For example, employees or departments Organized into rows and columns Field: an individual piece of data pertaining to an item, an employee name for instance Record: the complete data about a single item such as all information about an employee A record is a row of a table

6 Chapter 10, Slide 6Starting Out with Visual Basic 3 rd Edition Database Table Row (Record) ColumnField Each table has a primary key Uniquely identifies that row of the table PartNumber is the primary key in this example Columns also called fields or attributes Each column has a particular data type

7 Chapter 10, Slide 7Starting Out with Visual Basic 3 rd Edition VB and Access Data Types VB data types must match table data types MS Access and VB have similar data types Access Data TypeVisual Basic Data Type AutoNumberLong Date/TimeDate, DateTime Number, IntegerInteger Number, long integerLong Integer Number, singleSingle Number, doubleDouble TextString Yes/NoBoolean

8 Chapter 10, Slide 8Starting Out with Visual Basic 3 rd Edition Database Design A database schema is the design of tables, columns, and relationships between tables Define a column for each piece of data Allow plenty of space for text fields For the members of an organization: Column NameTypeSize First_NameText40 Last_NameText40 PhoneText30 Text40 Date_JoinedDate/Time OfficerYes/No1

9 Chapter 10, Slide 9Starting Out with Visual Basic 3 rd Edition Issues with Redundant Data Database design minimizes redundant data In the following employee table: IDFirst_NameLast_NameDepartment IgnacioFletaAccounting ChristianMartinComputer Support OrvilleGibsonHuman Resources 00300JoseRamirezResearch & Devel BenSmithAccounting AllisonChongComputer Support Same dept name appears multiple times Requires additional storage space Causes problems if misspelled What if a department needs to be renamed?

10 Chapter 10, Slide 10Starting Out with Visual Basic 3 rd Edition Eliminating Redundant Data Create a department table Dept_IDDept_NameNum_Employees 1Human Resources10 2Accounting5 3Computer Support30 4Research & Development15 Reference department table in employee table IDFirst_NameLast_NameDept_ID IgnacioFleta ChristianMartin OrvilleGibson JoseRamirez BenSmith AllisonChong3

11 Chapter 10, Slide 11Starting Out with Visual Basic 3 rd Edition One-to-Many Relationships The previous changes created a one-to- many relationship Every employee has one and only one dept Every department has many employees DeptID in department table is a primary key DeptID in employee table is a foreign key In general, a one-to-many relationship is created when the primary key of one table is specified as a field of a another table

12 Chapter 10, Slide 12Starting Out with Visual Basic 3 rd Edition Section 10.2 Using the DataGridView The DataGridView Control Allows you to Display a Database Table in a Grid Which Can be Used at Runtime to Sort and Edit the Contents of the Table

13 Chapter 10, Slide 13Starting Out with Visual Basic 3 rd Edition Connecting VB to a Database VB provides tools to display database tables Data binding links tables to form controls Controls called components establish the link A wizard guides you through the process Well use these data-related components: Data source – usually a database Binding source – holds database name, location, and other connection information Table adapter – uses SQL to select data Dataset – in-memory copy of data from tables

14 Chapter 10, Slide 14Starting Out with Visual Basic 3 rd Edition Connecting VB to a Database The flow of data from database to application Note that data moves in both directions Data travels from data source to application Application can view/change dataset contents Changes to dataset can be written back to the data source Tutorial 10-1 demonstrates how to connect a database table to a DataGridView control Data Source Binding Source Table Adapter DatasetApplication

15 Chapter 10, Slide 15Starting Out with Visual Basic 3 rd Edition Section 10.3 Selecting Dataset Rows Visual Basic Provides Convenient Tools for Selecting Which Rows from the Dataset You Want to Display

16 Chapter 10, Slide 16Starting Out with Visual Basic 3 rd Edition Structured Query Language (SQL) Often need to select certain rows in a table using Structured Query Language (SQL) Standard method of working with a database Adopted by most all database software Not a general purpose programming language Defines how to construct queries that return selected data from the database

17 Chapter 10, Slide 17Starting Out with Visual Basic 3 rd Edition SQL Query Example You might want to select all employees hired before 1998 and earning less than $45,000 Select ID, Name, Full_Time, Hire_Date, Salary From employees Where Hire_Date < 1/1/1998 and Salary < Select, From, and Where are keywords Fields to be returned listed after Select Table containing the data listed after From Conditions affecting row selection after Where SQL query is a property of the TableAdapter

18 Chapter 10, Slide 18Starting Out with Visual Basic 3 rd Edition Configuring the TableAdapter Right-click on dataset and select Configure to start TableAdapter Configuration Wizard Can modify a simple query directly in wizard Or use Query Builder for more complex query Query Builder is a tool to create or modify queries with minimal knowledge of SQL To add a query to a DataGridView Right-click Table Adapter icon attached to grid Select Add Query from shortcut menu Tutorial 10-2 demonstrates how this is done

19 Chapter 10, Slide 19Starting Out with Visual Basic 3 rd Edition Section 10.4 Data-Bound Controls Some Controls Can Be Bound to a Dataset. A Data-bound Control Can be Used to Display and Edit the Contents of a Particular Row and Co.lumn

20 Chapter 10, Slide 20Starting Out with Visual Basic 3 rd Edition

21 Chapter 10, Slide 21Starting Out with Visual Basic 3 rd Edition Advantages of Data-Binding Can add multiple data sources to a project Can bind fields in a data source to controls: Text boxes Labels List boxes Contents of data-bound controls change automatically when moving from row to row Updating the contents of a database field from a data-bound control is also very easy

22 Chapter 10, Slide 22Starting Out with Visual Basic 3 rd Edition Binding Existing Dataset to DataGrid Use the Data Sources window Locate the dataset table Drag table to an open area of a form Creates a data grid bound to the data source Automatically adds a navigation bar to form Set Dock property to Center Docking to make the data grid fill the entire form

23 Chapter 10, Slide 23Starting Out with Visual Basic 3 rd Edition Binding Individual Fields to Controls Use the Data Sources window Locate the dataset table Select Details from the table drop-down list Drag table to an open area of a form Creates a separate control for each field Can also drag columns individually Adds automatic navigation bar as before Text and numeric fields added as text boxes Yes/No fields added as checkboxes May wish to change some control properties

24 Chapter 10, Slide 24Starting Out with Visual Basic 3 rd Edition Binding to List and Combo Boxes List and combo boxes are frequently used to supply a list of items for a user to select from Such lists are often populated from a table Must set two list/combo box properties DataSource identifies a table within a dataset DisplayMember identifes the table column to be displayed in the list/combo box If table column dragged onto a list/combo box Visual Studio creates the required dataset, table adapter, and binding source components Tutorial 10-3 shows this type of binding

25 Chapter 10, Slide 25Starting Out with Visual Basic 3 rd Edition Adding New Rows to a Dataset NewRow method creates a new, empty row Assign values to columns in the empty row Add method appends new row to the dataset The following example adds a new row to the Payments table of the dsPayments dataset Dim row as dsPayments.PaymentsRow Row = CType(DsPayments.Payments.NewRow(), _ dsPayments.PaymentsRow) With row row.Member_ID = 5 row.Payment_Date = #5/15/2006# row.Amount = 500D End With DsPayments.Payments.Rows.Add(row)

26 Chapter 10, Slide 26Starting Out with Visual Basic 3 rd Edition Another Means to Add Dataset Rows Can call the dataset Add method directly This approach is more straightforward but: Must specify values in correct column order Previous example becomes far simpler: DsPayments.Payments.Rows.Add( _ Nothing, 5, #5/15/2006#, 500D) Payments table 1 st column is autonumber so: Must have an argument for this column Pass Nothing as the value for this column

27 Chapter 10, Slide 27Starting Out with Visual Basic 3 rd Edition Removing a Row from a Dataset Two steps to remove a row Get a reference to the row to remove Call Remove method on Rows collection Following example calls FindByID with the primary key to get a reference to the row Dim row as DataRow = _ DsPayments.Payments.FindByID(36) DsPayments.Payments.Rows.Remove(row)

28 Chapter 10, Slide 28Starting Out with Visual Basic 3 rd Edition Updating the Database Previous add and remove examples change the dataset but not the underlying database Must call TableAdapter Update method to save dataset changes to the database To write changes in the DsPayments dataset to the underlying database: PaymentsTableAdapter.Update(DsPayments) Tutorial 10-4 demonstrates adding new rows to the Payments table

29 Chapter 10, Slide 29Starting Out with Visual Basic 3 rd Edition Reading Dataset Rows with For-Each A For-Each statement can be used to iterate over all rows of a dataset Usually use a strongly typed dataset for this Sum Amount column of dsPayments dataset Dim row as dsPayments.PaymentsRow Dim decTotal as Decimal = 0 For Each row in DsPayments.Payments.Rows decTotal += row.Amount Next Tutorial 10-5 demonstrates this technique

30 Chapter 10, Slide 30Starting Out with Visual Basic 3 rd Edition Section 10.5 Structured Query Language (SQL) SQL Is a Standard Language for Working With Databases

31 Chapter 10, Slide 31Starting Out with Visual Basic 3 rd Edition The Select Statement Select retrieves rows from one or more tables in a database Basic form of Select for a single table is Select column-list From table column-list contains column names to select from table, each separated by a comma The following Select statement retrieves the ID and Salary fields from the SalesStaff table Select ID, Salary From SalesStaff

32 Chapter 10, Slide 32Starting Out with Visual Basic 3 rd Edition Column Names Use asterisk to select all columns in a table Select * From SalesStaff Unlike VB names, SQL columns can have embedded spaces If so, use square brackets around column names Select [Last Name], [First Name] From SalesStaff Better to avoid embedded spaces for this reason As operator can be used to rename columns Select Last_Name, Hire_Date As Date_Hired From SalesStaff

33 Chapter 10, Slide 33Starting Out with Visual Basic 3 rd Edition Creating New Columns Sometimes useful to create a new column by appending existing columns together Create a Full_Name field from first and last name Select Last_Name +, + First_Name as Full_Name From SalesStaff Creates a Full_Name field in the format last, first Can also be useful to create a new column by performing arithmetic operations Columns involved must be numeric Select ID, hrsWorked * hourlyRate As payAmount From Payroll Creates a payAmount column with gross pay

34 Chapter 10, Slide 34Starting Out with Visual Basic 3 rd Edition Sorting Rows with Order By Clause SQL Select has an optional Order By clause that affects the order in which rows appear Order by Last_Name, First_Name Displays rows in order by last name, then first Sort in reverse order (high to low) using Desc Order by Last_Name DESC Order By clause appears after From clause Select First_Name, Last_Name, Date_Joined From Members Order By Last_Name, First_Name Lists all members by last name, then first

35 Chapter 10, Slide 35Starting Out with Visual Basic 3 rd Edition Selecting Rows with Where Clause SQL Select has an optional Where clause that can be used to select (or filter) certain rows Where Last_Name = Gomez Displays only rows where last name is Gomez Must be a defined column (in table or created) This example selects based on a created field Select Last_Name, hrsWorked * Rate As payAmount From Payroll Where payAmount > 1000 Order by Last_Name Selects those being paid more than $1,000

36 Chapter 10, Slide 36Starting Out with Visual Basic 3 rd Edition SQL Relational Operators SQL Where uses relational operators just like a VB If OperatorMeaning =equal to <>not equal to greater than >=greater than or equal to Betweenbetween two values (inclusive) Likesimilar to (match using wildcard) Example of Between operator: Where Hire_Date Between #1/1/1992# and #12/31/1999# Example of Like operator with % sign as wildcard: Where Last_Name Like A%

37 Chapter 10, Slide 37Starting Out with Visual Basic 3 rd Edition Compound Expressions SQL uses And, Or, and Not to create compound expressions Select all employees hired after 1/1/1990 and with a salary is greater than $40,000 Where (Hire_Date > #1/1/1990#) and (Salary > 40000) Select all employees hired after 1/1/1990 or with a salary is greater than $40,000 Where (Hire_Date > #1/1/1990#) or (Salary > 40000) Select employee names not beginning with A Where Last_Name Not Like A%

38 Chapter 10, Slide 38Starting Out with Visual Basic 3 rd Edition Section 10.6 Karate School Management Application Create an Application that Works With the Karate School Database


Download ppt "Chapter 10, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 10 Working With Databases."

Similar presentations


Ads by Google