Download Chapter 10 - Pearson Higher Education

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Microsoft Jet Database Engine wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Database wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

SQL wikipedia , lookup

Functional Database Model wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Clusterpoint wikipedia , lookup

Relational model wikipedia , lookup

Object-relational impedance mismatch wikipedia , lookup

Database model wikipedia , lookup

Transcript
STARTING OUT WITH
Visual Basic 2008
FOURTH EDITION
Tony Gaddis
Haywood Community College
Kip Irvine
Florida International University
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 1
Chapter
10
Working With Databases
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Introduction





Basic database terminology
Fundamental database concepts
Use ADO .NET to access databases
Display, sort, and update database data
Use the DataGridView control
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 3
10.1
Database Management
Systems
Visual Basic applications use database
management systems to make large
amounts of data available to programs
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Visual Basic and Database
Management Systems



Simple text files as shown in chapter 9 are:
 Fine for small amounts of data
 But impractical for large amounts of data
Businesses must maintain huge amounts of data
 A database management system (DBMS) is the
typical solution to the data needs of business
 Designed to store, retrieve, & manipulate data
Visual Basic can communicate with a DBMS
 Tells DBMS what data to retrieve or manipulate
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 5
Layered Approach to Using a DBMS


Applications that work with a
DBMS use a layered approach
 VB application is topmost layer
 VB sends instructions to next
layer, the DBMS
 DBMS works directly with data
Programmer need not understand
the physical structure of the data
 Just need to know how to
interact with the database
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 6
Visual Basic Supports Many DBMS’s


Visual Basic can interact with many DBMS’s
 Microsoft SQL Server
 Oracle
 DB2
 MySQL
Microsoft SQL Server 2008 Express used in this
chapter
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 7
10.2
Database Concepts
A database is a collection of one or
more tables, each containing data
related to a particular topic
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 9
Database Table



Each table has a primary key
 Uniquely identifies that row of the table
 Emp_Id is the primary key in this example
Columns are also called fields or attributes
Each column has a particular data type
Row
(Record)
Emp_Id
First_Name
Last_Name
Department
001234
Ignacio
Fleta
Accounting
002000
Christian
Martin
Computer Support
002122
Orville
Gibson
Human Resources
003400
Ben
Smith
Accounting
003780
Allison
Chong
Computer Support
Column
Field
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 10
VB and SQL Server Data Types


VB data types must match table data types
SQL Server and VB have similar data types
SQL Type
Usage
Visual Basic Type
Bit
DateTime
Decimal, Money
Float
Int
Smallint
Varchar(n)
Text
True/false values
Dates and times
Financial values
Real-number values
Integer values
Integers -32,768 to 32,767
Variable length strings
Strings more than 8000 char
Boolean
Date, DateTime
Decimal
Double
Integer
Short
String
String
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 11
Choosing Column Names




Define a column for each piece of data
Allow plenty of space for text fields
Avoid using spaces in column names
For the members of an organization:
Column Name
Type
Remarks
Member_ID
First_Name
Last_Name
Phone
Email
Date_Joined
Meeings_Attended
Officer
int
varchar(40)
varchar(40)
varchar(30)
varchar(50)
smalldatetime
smallint
Yes/No
Primary key
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Date only, no time values
True/False values
Slide 10- 12
Issues with Redundant Data


Database design minimizes redundant data
In the following employee table:
ID
001234
002000
002122
00300
003400
003780

First_Name
Ignacio
Christian
Orville
Jose
Ben
Allison
Last_Name
Fleta
Martin
Gibson
Ramirez
Smith
Chong
Department
Accounting
Computer Support
Human Resources
Research & Devel
Accounting
Computer Support
Same dept name appears multiple times
 Requires additional storage space
 Causes problems if misspelled
 What if a department needs to be renamed?
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 13
Eliminating Redundant Data

Create a department table
Dept_ID
1
2
3
4

Dept_Name
Human Resources
Accounting
Computer Support
Research & Development
Num_Employees
10
5
30
15
Reference department table in employee table
ID
001234
002000
002122
003000
003400
003780
First_Name
Ignacio
Christian
Orville
Jose
Ben
Allison
Last_Name
Fleta
Martin
Gibson
Ramirez
Smith
Chong
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Dept_ID
2
3
1
4
2
3
Slide 10- 14
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
One-to-many relationship
exists when primary key
of one table is specified
as a field of another table
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 15
10.3
DataGridView Control
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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Connecting VB to a Database



VB provides tools to display database tables
Data binding links tables to controls on forms
 Controls called components establish the link
 A wizard guides you through the process
We’ll use these data-related components:
 Data source – usually a database
 Binding source – connects data bound
controls to a dataset
 Table adapter – uses SQL to select data
 Dataset – in-memory copy of data from tables
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 17
Connecting VB to a Database

The flow of data from database to application
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


Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 18
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 Column
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Advantages of Data-Binding



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
Data-bound control also allow the contents of a
database field to be changed
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 20
Adding a New Data Source



Open the Data Sources window
Click the Add New Data Source
link
Follow the steps in the
Data Source Configuration
Wizard to create a
connection to the database
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 21
Deleting a Data Source




Once created, it’s almost impossible to rename a
data source
Easier to delete and create a new data source
than rename one
A data source named Employees for example
would be defined by a file named Employees.xsd
To delete this data source:
 Select Employees.xsd file in Solution Explorer
 Press Delete
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 22
Binding Existing Dataset to DataGrid



If you wish to bind a dataset already found in the
Data Sources window
 Locate the table in the Data Sources window
 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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 23
Binding Individual Fields to Controls






Use the dataset in the Data Sources window
 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
Text and numeric fields added as text boxes
Yes/No fields added as checkboxes
DateTime fields use DateTimePicker controls
May wish to change some control properties
Tutorial 10-3 & 10-4 demonstrate binding
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 24
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-5 demonstrates binding to a list box
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 25
Adding Rows to a Database Table



A data source has a schema definition file (.xsd)
An .xsd file was created in Tutorial 10-5 for the
Members table
 DataTable created when data source added
 TableAdapter object created for the DataTable
A TableAdapter object has an Insert method
 Used to add a new row to the database table
 Each column is an argument of the method
 Just provide the values for each argument
MembersTableAdapter.Insert(10, “Hasegawa”, _
“Adrian”, “305-999-8888”, #5/15/2008#)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 26
Identity Columns


Some database tables have an identity column
 Assigned a unique number by the database
 Occurs automatically for identity columns
 Thus no need to supply a value for this column
Payments table uses an identity column
 So omit ID column value
 Supply Member_Id, Payment_Date, & Amount
PaymentsTableAdapter.Insert(5, #5/15/2008#, 50D)

Tutorial 10-6 adds a row to the Payments table
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 27
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 PaymentsDataSet.PaymentsRow
Dim decTotal as Decimal = 0
For Each row in Me.PaymentsDataSet.Payments.Rows
decTotal += row.Amount
Next

Tutorial 10-7 demonstrates this technique
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 28
10.5
Structured Query Language
(SQL)
SQL Is a Standard Language for
Working With Databases
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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
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


column-list
Select ID, Salary
From SalesStaff
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 30
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 Employees
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 31
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 Members


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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 32
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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 33
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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 34
SQL Relational Operators


SQL Where uses relational operators just like a VB If
Operator
Meaning
=
<>
<
<=
>
>=
Between
Like
equal to
not equal to
less than
less than or equal to
greater than
greater than or equal to
between two values (inclusive)
similar 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%’
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 35
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%’
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 36
Modifying a Query in a Data Source


Dataset schema file contains an SQL query
 Created as part of schema file
 Named Fill, GetData() by default
Right-click title bar
of TableAdapter in schema
 Click Configure from pop-up
 Use Configuration Wizard
to change simple queries
 Query Builder often used
for complex queries
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 37
Query Builder


Visual Studio tool to work with SQL queries
Consists of 4 sections or panes
 Diagram pane
displays tables
 Grid pane displays
query in
spreadsheet form
 SQL pane shows
actual SQL created
 Results pane shows data returned by query
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 38
Adding a Query to a DataGridView






Can add a new query as well as changing an
existing one
Right-click table adapter icon
in component tray
Select Add Query to display
Search Criteria Builder
Add Where clause
Click New query name radio
button enter a name for query
Query made available from ToolStrip control
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 39
10.6
Karate School
Management Application
Create an Application that Works
With the Karate School Database
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Karate School Startup Form
Menu Selections:
 File
• Exit
 Membership
• List All
• Find member
• Add new member
 Payments
• All members
• One member
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 41
Karate School Member Forms
All Members Form
Add New Member Form
Find Member by
Last Name Form
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 10- 42
Karate School Payments Forms
Payments by All Members Form
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Payments by One
Member Form
Slide 10- 43