Chapter 23

Relational Databases


Chapter Goals

Relational Database

Product Table in a Relational Database

Product Table in a Relational Database

Product Table

SQL

Some SQL Types and Their Corresponding Java Types

SQL Types vs Java Types

SQL to Create a Table

CREATE TABLE Products
(
    Product_Code CHAR(11)
    Description CHAR(40)
    Unit_Price DECIMAL(10, 2)
)

SQL to Add Data to a Database

INSERT INTO Products
    VALUES ('3554-0632-1', 'Hair dryer', 29.95)

Linking Tables

Poor Design for an Invoice Table with Replicated Customer Data

Poor Design

Two Tables for Invoice and Customer Data

Two Tables for Invoice and Customer Data

Linking Tables

Linking Tables

Implementing One-to-Many Relationships

Poor Design for Invoice Table with Replicated Columns

replicated columns

Linked Invoice and Item Tables

Linked invoice and item

Sample Database

sample database

Queries

Simple Query

Selecting Columns

columns

Selecting Subsets

Result of SELECT * FROM Customer WHERE State = 'CA'

Subsets

Selecting Subsets

Selecting Subsets

Calculations

Joins

Joins

Updating and Deleting Data

Updating and Deleting Data

File TestDB.java

File SimpleDataSource.java

File database.properties

Connecting to the DataBase

Connecting to the Database

Connecting to the Database

Executing SQL Statements

Executing SQL Statements

Executing SQL Statements

Executing SQL Statements

Analyzing Query Results

Analyzing Query Results

Analyzing Query Results

Result Set Meta Data

Result Set Meta Data

Result Set Meta Data

File cityzone.sql

File ExecSQL.java

Case Study: A Bank Database

Tables for ATMSimulation

customer table
account table

Case Study: A Bank Database

Case Study: A Bank Database

public Customer find(int customerNumber, int pin)
    throws SQLException
{
   Customer c = null;
   Connection conn = SimpleDataSource.getConnection();
   Statement stat = conn.createStatement();
   ResultSet result = stat.executeQuery("SELECT *"
      + " FROM Customer WHERE Customer_Number = "
      + customerNumber);

   if (result.next() && pin == result.getInt("PIN"))
      c = new Customer(customerNumber,
         result.getInt("Checking_Account_Number"),
         result.getInt("Savings_Account_Number"));
   result.close();
   stat.close();
   conn.close();
   return c;
}

Case Study: A Bank Database

File ATMSimulation.java

File ATM.java

File Bank.java

File BankAccount.java

File Customer.java

Transactions

Transactions

Transactions

Scrollable and Updatable Result Sets

Scrollable and Updatable Result Sets

Scrollable and Updatable Result Sets

Scrollable and Updatable Result Sets

Updatable Result Sets

Updatable Result Sets

Speeding Queries Up

Indexing

Prepared Statements

Prepared Statements

Stored Procedures

Stored Procedures

Stored Procedures