Download Chapter 7

Document related concepts

Microsoft Jet Database Engine wikipedia , lookup

SQL wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Clusterpoint wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
Advanced Visual Basic 2005
4th Edition
by Kip Irvine and Tony Gaddis
Chapter 3: Using SQL
Server Databases
Slides prepared by the authors
Revision date: Jan 18, 2007
(c) 2007 Pearson Education Inc. All rights reserved. You may modify and copy this slide show for your personal use, or
for use in the classroom, as long as this copyright statement, the author's names and title are not changed.
Overview
•
•
•
•
•
•
Database Basics
SQL SELECT Statement
Using the DataGridView
Selecting DataSet Rows
Data-Bound Controls
Karate School Manager Application
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
2
Database Basics
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
3
Introduction
• Database holds collection of tables
• Table is logical grouping of related information
• rows – each row holds a logical unit
• columns – similar to attributes
• Example:
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
4
Primary Key
•
•
•
•
Column or columns that uniquely identify each row
Can be any data type
Can be auto-generated (identity)
Departments table:
• dept_id column is the primary key
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
5
SQL Server Data Types
• Microsoft SQL Server
• .NET uses SqlDbType to identify data types
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
6
Designing Database Tables
• Database schema
• design of tables, columns, and relationships
• Choose descriptive column names
• Use data types that match the data values
• Sample Members table:
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
7
Sample Column Types
•
•
•
•
•
•
•
Primary key – Int type
Person's last name: VarChar type
Salary: Decimal type
Ratio: Float type
Boolean (True/False): Bit type
Birth date: DateTime or SmallDateTime type
Picture: Image type
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
8
One-To-Many Relationship
• Relational model
• relations between tables
• minimizes duplication of data within table rows
• Primary Key referenced by Foreign Key
• Example:
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
9
Checkpoint
1. How is a table different from a database?
2. In a table of employees, what column would make a
good primary key?
3. Which Visual Basic data type is equivalent to the Bit
column type in SQL Server?
4. Why would we not want to spell out the name of
each person’s department name in a table of
employees?
5. How is a foreign key different from a primary key?
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
10
SQL SELECT Statement
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
11
SELECT Statement
• SQL – Structured Query Language
• Standardized by ANSI (American National Standards
Institute)
• SELECT returns rows from one or more tables
• Example 1:
SELECT ID, Salary
FROM SalesStaff
• Example 2:
SELECT [Last Name], [First Name]
FROM Employees
• Example 3:
SELECT *
FROM SalesStaff
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
12
Setting the Row Order with ORDER BY
• Format:
ORDER BY columnName [ASC | DESC]
• Examples:
ORDER
ORDER
ORDER
ORDER
BY
BY
BY
BY
Last_Name ASC
Last_Name
Last_Name DESC
Last_Name, First_Name
• Complete example:
SELECT ID, Salary
FROM SalesStaff
ORDER BY ID
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
13
Selecting Rows with the WHERE Clause
• WHERE clause filters (selects) rows returned by the
SELECT statement
• Simplest format
WHERE columnName = value
• Example:
SELECT First_Name, Last_Name, Salary
FROM SalesStaff
WHERE Last_Name = 'Gomez'
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
14
Relational Operators
• Operators permitted in WHERE clause expressions:
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
15
Numeric and Date Values
• Numeric literals have no delimiters or commas
• Parentheses are optional
WHERE Salary > 30000
WHERE (Salary > 30000)
• DateTime values are delimited by single quotes
WHERE (Hire_Date > '12/31/1999')
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
16
Checkpoint
1. Write a SELECT statement that retrieves the pay_rate, employee_id,
and hours_worked columns from a table named Payroll, and sorts the
rows in descending order by hours_worked.
2. Write a SELECT statement that creates an alias named Rate_of_Pay
for the existing column named pay_rate in the Payroll table.
3. Write a SELECT statement for the Payroll table that creates a new
output column named gross_pay by multiplying the pay_rate column by
the hours_worked column.
4. Write a SELECT statement for the Payroll table that returns only rows
in which the pay_rate is greater than 20,000 and less than or equal to
55,000.
5. Write a SELECT statement for the Payroll table that returns only rows
in which the employee_id column begins with the characters FT. The
remaining characters in the employee_id are unimportant.
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
17
Using the DataGridView
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
18
Introducing the DataGridView
•
•
•
•
Displays data in rows and columns
Usually bound to a DataTable
User can add, edit, and delete rows
Customizable (design time & run time)
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
19
Data-Related Components
• Data source
• connects to database or file containing data
• TableAdapter
• transfers data from data source to the application
• may also update the data source
• DataSet
• in-memory copy of data from the data source
• filled by TableAdapter
• BindingSource
• optional link between DataSet and bound controls
Binding
Source
Data
Source
Table
Adapter
DataSet
Application
(Information flows in both directions)
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
20
Formatting Columns in a DataGridView
• Select the Columns property
• DefaultCellStyle property
• Format property
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
21
Tutorial 3-1
• Showing a database table in a DataGridView control
• SalesStaff table in the Company database
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
22
Tutorial 3-1
• Configure the DataGridView tasks
• Add a new connection
• VS copies database into the
project folder
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
23
Tutorial 3-1 (continued)
• Select the SalesStaff table
• Display in a DataGridView
• Fill the SalesStaff DataTable:
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
24
Checkpoint
1. Using the application you created in Tutorial 3-1, explain how to
change the formatting of the Salary column so it displays
values in currency format.
2. The technique called ________ links database tables to
controls on Visual Basic forms.
3. Which component pulls data from one or more database tables
and passes it into a DataSet?
4. When changes are made to a DataSet at runtime, what
happens to the database that filled the DataSet?
5. Which control displays DataSets in a spreadsheet-like format?
6. What type of object connects a program to a database?
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
25
Selecting DataSet Rows
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
26
SQL
• Structured Query Language
• commonly used statements
SELECT, DELETE, INSERT, UPDATE, ...
• SELECT queries a database
• retrieves rows
• Updating a database
• INSERT
• DELETE
• UPDATE
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
27
Modifying the Query in a Data Source
• Locate DataSet's schema file in the Solution Explorer
window
• open the DataSet designer tool:
• Use Query Builder:
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
28
Query Builder
•
•
•
•
Diagram pane
Grid pane
SQL pane
Results pane
diagram pane
grid pane
SQL pane
result pane
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
29
Adding a SELECT Query to a DataGridView
• Right-click the TableAdapter icon
• select Add Query
• Search Criteria Builder window
• ToolStrip added to the form, containing a button
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
30
Tutorial 3-2
• Filtering rows in the SalesStaff table
• Display results in a DataGridView
• Query:
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
31
Checkpoint
1. What does the acronym SQL represent, in relation to
databases?
2. Why do SQL queries work with any relational
database?
3. Write an SQL SELECT statement that retrieves the
First_Name and Last_Name columns from a table
named Employees.
4. How do you add a query to a TableAdapter in the
component tray of a form?
5. Write a WHERE clause in SQL that limits the
returned data to rows in which Salary is less than or
equal to $85,000.
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
32
Data-Bound Controls
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
33
Describing Data-Bound Controls
• Automatically display the contents of the current table
or table row
• Update their contents automatically when the user
moves through rows in a DataSet
• Can update the contents of the DataSet
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
34
Visual Studio Copies Database Files
• When you attach an SQL Server database file
• Makes a local copy of the database
• Updates made at runtime only affect a temporary copy
of the database
• saved in the \bin\Debug or \bin\Release folder
• replaced each time the program runs
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
35
Modifying a Connection String
• Right-click project name in Solution Explorer window
• select the Settings tab
• click the Browse button
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
36
Binding Data Source to DataGridView
• Existing data source
• Drag onto a form
• VS inserts a DataGridView and navigation bar
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
37
Binding Individual Fields to Columns
• Select Details in the table's dropdown
list inside the Data Sources window
• Drag the table onto a form
• or drag individual columns onto the form
• select control binding type
• edit the fields as needed
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
38
Introducing the Karate Database
• Karate school management database
• Tables
• Members
• Payments
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
39
Binding Data Sources to ListBoxes and
ComboBoxes
• DataSource property
• identifies the DataTable supplying
the data
• DisplayMember property
• identifies the displayed column
• ListBox or ComboBox can be used as a navigation or
selection tool
• BindingSource repositions itself to the selected row
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
40
Tutorial 3-3
• Displaying the Members table in a ListBox
• add a new data source (Members table)
• attach it to the ListBox's DataSource property
• set the ListBox's DisplayMember property
• Run the application
• when user selects a last name, the member's detailed
fields are displayed:
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
41
Adding Rows to DataSet Tables
• NewRow method
• creates and returns an empty row with same structure
as the DataSet table:
Dim row as DataRow = _
PaymentsDataSet.Payments.NewRow(
• Add method
• adds a row to the table
• pass it the column values
• pass Nothing for autoincrement columns
PaymentsDataSet.Payments.Rows.Add(Nothing, _
5, '5/15/2006', 50D)
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
42
Updating, Inserting, Removing Rows
• TableAdapter Update method
• writes changes to the underlying database
PaymentsTableAdapter.Update(PaymentsDataSet)
• TableAdapter Insert method
• inserts a new row in a table
PaymentsTableAdapter.Insert(5, '5/15/2006', 50D)
• DataRow Remove method
• requires a reference to a table row
Dim row As DataRow = _
PaymentsDataSet.Payments.FindByID(36)
PaymentsDataSet.Payments.Rows.Remove(row)
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
43
Tutorial 3-4
• Inserting rows in the Karate Payments table
• uses DataGridView control
• calls the TableAdapter's Insert method
txtMemberId
txtDate
txtAmount
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
44
Using Loops with DataSets
• Iterate over the Rows collection of a DataTable
• For-Each loop
• Example, using the Karate Payments table:
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
45
Tutorial 3-5
• Adding a total to the Insert_Karate_Payments
application
• continues Tutorial 3-4
• Click handler for the Total Payments
button:
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
46
Checkpoint
1. Which Visual Studio window displays the list of data sources
belonging to a project?
2. The ______ Configuration Wizard is a tool you can use to
create a connection to a database and select a database table.
3. If a certain DataTable already exists, what is the easiest way to
bind it to a DataGridView control?
4. How do you bind a single DataSet column to a text box?
5. By default, which control binds to a DateTime field in a
DataSet?
6. What is the menu command for adding a new DataSet to the
current project?
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
47
Karate School Manager Application
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
48
Features
1. Displays a list of all members
2. Permits the user to sort on any column, edit
individual rows, and delete rows
3. Adds new students to the list of members
4. Finds a member by letting the user enter a partial
last name
5. Displays payments by all members, sorting on any
column
6. Displays a list of payments by one member
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
49
Main Form
• Starts the application
• File, Membership, and Payments menus
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
50
Membership Forms
• All Members
• Find Member by Last Name
• Add New Member
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
51
Payments Forms
• Payments by All Members
• sort on any column
• Payments by One Member
• select member from ComboBox
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
52
Tutorials 3-6 and 3-7
• Tutorial 3-6
• Creating the Karate School Manager startup form
• Tutorial 3-7
• Listing all members
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
53
Using a BindingSource
• Connection between DataSet and the data-bound
controls on a form
• updates the DataSet when user modifies data in bound
controls
• Items collection
• BindingSource class methods and properties
• DataSource
• AddNew
• RemoveCurrent
• EndEdit
• CancelEdit
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
54
Tutorial 3-8
• Karate School Manager: Adding new members
• Members table
• uses data binding
• writes changes to a temporary copy of database
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
55
Using Query Parameters
• Create simpler, more flexible SQL queries
• Avoid concatenating SQL statements to control names:
• Define parameter name with @ prefix:
• TableAdapter's Fill method has a new parameter:
MembersTableAdapter.Fill( _
Me.FindMemberDataSet.Members, txtLastName.Text)
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
56
Wildcard Matches in SQL Queries
• Use the LIKE operator
• % matches any character string
• Example
• Returns all last names starting with letter G:
WHERE Last_name LIKE 'G%'
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
57
Tutorial 3-9
• Karate School Manager: Finding members by name
• accepts partial name string
• uses query parameter
• uses LIKE operator with wildcard matches
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
58
Tutorial 3-10
• Karate School Manager: Listing payments by all
members
• joins Payments, Members
tables
• uses DataGridView control
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
59
Tutorial 3-11
• Karate School Manager: Showing payments by one
member
• user selects name from ComboBox
• payments shown in DataGridView
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
60
Checkpoint
1. In the Karate database, which table contains the
names and dates when students joined the school?
2. In the PaymentsAllForm form, which two tables are
required when filling the grid?
3. Which property of a DataGridView control lets you
alter the order in which columns appear?
4. How does the PaymentsOneForm form obtain the ID
number of the member selected by the user in the
ComboBox?
5. What special keyword is used in the WHERE clause
of a query when you want to perform a wildcard
comparison?
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
61
Summary
•
•
•
•
•
•
Database Basics
SQL SELECT Statement
Using the DataGridView
Selecting DataSet Rows
Data-Bound Controls
Karate School Manager Application
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
62
The End
Advanced Visual Basic 2005, 4th Edition. © Pearson Education Inc.
63