SlideShare a Scribd company logo
1 of 71
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
C HA PT E R 16
Databases
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Topics
Introduction to Database Management
Systems
Tables, Rows, and Columns
Introduction to the SQL SELECT Statement
Inserting Rows
Updating and Deleting Existing Rows
Creating and Deleting Tables
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Topics
Creating a New Database with JDBC
Scrollable Result Sets
Result Set Meta Data
Displaying Query Results in a Jtable
Relational Data
Advanced Topics
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Introduction to Database
Management Systems
Storing data in traditional text or binary files
has its limits
well suited for applications that store only a small
amount of data
not practical for applications that must store a large
amount of data
simple operations become cumbersome and
inefficient as data increases
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Introduction to Database
Management Systems
A database management system (DBMS) is
software that is specifically designed to work
with large amounts of data in an efficient and
organized manner
Data is stored using the database management
system
Applications written in Java or other languages
communicate with the DBMS rather than
manipulate the data directly
DBMS carries out instructions and sends the
results back to the application
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Application sends a
command to the DBMS
The DBMS executes the
command on the Data
The Application displays
the result to the user
The DBMS sends the
result back to the
Application
Introduction to Database Management
Systems
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
JDBC
JDBC stands for Java
database connectivity
It is the technology that
makes communication
possible between the Java
application and DBMS
The Java API contains
numerous JDBC classes that
allow your Java applications
to interact with a DBMS
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
SQL
SQL stands for structured query language
A standard language for working with database
management systems
Not used as a general programming language
Consists of several key words, used to construct
statements known as queries
Statements or queries are strings passed from the
application to the DBMS using API method calls
Serve as instructions for the DBMS to carry out
operations on its data
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Using a DBMS
To use JDBC to work with a database you will need a
DBMS
Oracle
Microsoft SQL Server
DB2
MySQL
Java DB
The examples in this chapter were created with Java
DB
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Java DB
Java DB is an open source distribution
of Apache Derby, a pure Java DBMS
that is made freely available from
Oracle.
It is designed specifically for Java
applications and is easy to install and
use. All of the examples in this chapter
were created with Java DB.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Creating the CoffeeDB
Database
In this chapter we will use a database named
CoffeeDB as our example.
After you have installed the Java DB DBMS, perform
the following steps to create the CoffeeDB
database:
Make sure you have downloaded Student Source
Code files from the book's companion Web site.
In this chapter's source code files, locate a program
named CreateCoffeeDB.java.
Compile and execute the CreateCoffeeDB.java
program. If Java DB is properly installed, this
program will create the CoffeeDB database on your
system.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Connecting to the CoffeeDB
Database
The static DriverManager.getConnection method is
used to get a connection to the database
General format of the simplest version:
General format if a user name and a password are required:
Username is a string containing a valid username
Password is a string containing a password
DatabaseURL lists the protocol used to access the database
DriverManager.getConnection(DatabaseURL);
DriverManager.getConnection(DatabaseURL,
Username,
Password);
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Connecting to the CoffeeDB
Database
DatabaseURL is a string known as a database URL
URL stands for uniform resource locator
A simple database URL has the following general format:
protocol is the database protocol
value is jdbc when using JDBC
subprotocol varies depending on the type of DBMS
value is derby when using Java DB
databaseName is the name of the database
Using Java DB, the URL for the CoffeeDB database is:
protocol:subprotocol:databaseName
jdbc:derby:CoffeeDB
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Connecting to the CoffeeDB
Database
The DriverManager.getConnection method
Searches for and loads a compatible JDBC driver for
the database specified by the URL
Returns a reference to a Connection object
Should be saved in a variable, so it can be used
later (more on this in a moment)
Throws an SQLException if it fails to load a
compatible JDBC driver
Example: TestConnection.java
Final String DB_URL = "jdbc:derby:CoffeeDB";
Connection conn = DriverManager.getConnection(DB_URL);
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Tables, Rows, and Columns
A database management system stores data
in a database
A database is organized into one or more
tables
Each table holds a collection of related data,
organized into rows and columns
A row is a complete set of information about a
single item, divided into columns
Each column is an individual piece of
information about the item
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Database Organization
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Coffee database table
Each row
contains data
for a single
item.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Column Data Types
• Columns in a database are assigned an SQL data type
– SQL data types are generally compatible with Java data types
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Coffee Table Column
Data Types
Description column data type is CHAR(25)
String with a fixed length of 25 characters
Compatible with the String type in Java
ProdNum column data type is CHAR(10)
String with a fixed length of 10 characters
Compatible with the String type in Java
Price column data type is DOUBLE
Double-precision floating-point number
Compatible with the double data type in Java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Primary Keys
A primary key is a column that holds a
unique value for each row in a database table
In the Coffee table, ProdNum is the primary
key
Each type of coffee has a unique product
number
Used to identify any coffee stored in the table
A primary key can be the combination of
several columns in a table
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The SQL SELECT Statement
The SELECT statement is used to retrieve the rows in
a table
Columns is one or more column names
Table is a table name
Example 1:
Example 2:
Multiple column names are separated with a comma
Example 3:
The * character can be used to retrieve all columns in the table
SELECT Columns FROM Table
SELECT Description FROM Coffee
SELECT Description, Price FROM Coffee
SELECT * FROM Coffee
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
More About SQL Statements
• SQL statements are free form
– tabs, new lines, and spaces between key words are ignored
• SQL key words and table names are case insensitive
• Example:
SELECT * FROM Coffee
SELECT
*
FROM
Coffee
select * from coffee
The following statements all work the same:
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Passing an SQL Statement to
the DBMS
Once you have established a connection, you must
get a reference to a Statement object before you
can issue SQL statements to the DBMS
A Statement object has an executeQuery method that
returns a reference to a ResultSet object
A ResultSet object contains the results of the query
Example:
Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = conn.createStatement();
String sqlStatement = "SELECT Description FROM Coffee";
ResultSet result = stmt.executeQuery(sqlStatement);
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Getting a Row from the
ResultSet Object
A ResultSet object has an internal cursor
Points to a specific row in the ResultSet
The row to which it points is the current row
Initially positioned just before the first row
Can be moved from row to row to examine all rows
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Getting a Row from the
ResultSet Object
A ResultSet object’s next method moves the cursor
to the next row in the ResultSet
moves to first row in a newly created ResultSet
moves to the next row each time it is called
result.next();
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Getting a Row from the
ResultSet Object
A ResultSet object’s next method returns a
Boolean value
true if successfully moved to the next row
false if there are no more rows
A while loop can be used to move through
all the rows of a newly created ResultSet
while (result.next())
{
// Process the current row.
}
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Getting Columns in a
ResultSet Object
You use one of the ResultSet object’s “get” methods to
retrieve the contents of a specific column in the current row.
Can pass an argument for either the column number or the
column name
System.out.println(result.getString(1));
System.out.println(result.getString(1));
System.out.println(result.getString(1));
System.out.println(result.getString("Description"));
System.out.println(result.getString("ProdNum"));
System.out.println(result.getDouble("Price"));
Examples: ShowCoffeeDescriptions.java
ShowDescriptionsAndPrices.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Getting Columns in a ResultSet Object
ResultSet Method Description
double getDouble(int
colNumber)
double getDouble(String
colName)
Returns the double that is stored in the
column specified by colNumber or
colName. The column must hold data that is
compatible with the double data type in Java.
If an error occurs, the method throws an
SQLException.
int getInt(int colNumber)
int getInt(String colName)
Returns the int that is stored in the column
specified by colNumber or colName. The
column must hold data that is compatible with
the int data type in Java. If an error occurs,
the method throws an SQLException.
String getString(int
colNumber)
String getString(String
colName)
Returns the string that is stored in the column
specified by colNumber or colName. The
column must hold data that is compatible with
the String type in Java. If an error occurs, the
method throws an SQLException.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Specifying Search Criteria
with the WHERE clause
The WHERE clause can be used with the SELECT statement to
specify a search criteria
Criteria is a conditional expression
Example:
Only the rows that meet the search criteria are returned in the result
set
A result set is an object that contains the results of an SQL statement
SELECT Columns FROM Table WHERE Criteria
SELECT * FROM Coffee WHERE Price > 12.00
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
SQL Relational Operators
Standard SQL supports the following relational
operators:
Notice a few SQL relational operators are different than in Java
SQL equal to operator is =
SQL not equal to operator is <>
Example: CoffeeMinPrice.java
Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
= Equal to
<> Not equal to
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
String Comparisons in SQL
Example 1:
In SQL, strings are enclosed in single quotes
Warning!
String comparisons in SQL are case sensitive
Example 2:
The UPPER() or LOWER() functions convert the string to uppercase or
lowercase and can help prevent case sensitive errors when comparing
strings
Example 3:
If a single quote (') is part of a string, use two single quotes ('')
SELECT * FROM Coffee WHERE Description ='Joe''s Special Blend'
SELECT * FROM Coffee
WHERE UPPER(Description) = 'FRENCH ROAST DARK'
SELECT * FROM Coffee WHERE Description = 'french roast dark'
SELECT * FROM Coffee WHERE Description = 'French Roast Dark'
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Using the LIKE Operator
In SQL, the LIKE operator can be used to search for
a substring
Example 1:
The % symbol is used as a wildcard for multiple characters
Example 2:
The underscore (_) is a used as a wildcard for a single
character
Example 3:
The NOT operator is used to disqualify the search criteria
SELECT * FROM Coffee WHERE Description LIKE '%Decaf%'
SELECT * FROM Coffee WHERE ProdNum LIKE '2_-00_'
SELECT * FROM Coffee
WHERE Description NOT LIKE '%Decaf%'
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Using AND and OR
The AND and OR operators can be used to specify
multiple search criteria in a WHERE clause
Example 1:
The AND operator requires that both search criteria be
true
Example 2:
The OR operator requires that either search criteria be
true
SELECT * FROM Coffee
WHERE Price > 10.00 AND Price < 14.00
SELECT * FROM Coffee
WHERE Description LIKE '%Dark%' OR ProdNum LIKE
'16%'
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Sorting the Results of a
SELECT Query
Use the ORDER BY clause to sort results
according to a column value
Example 1:
Sorted in ascending order (ASC) by default
Example 2:
Use the DESC operator to sort results in descending
order
SELECT * FROM Coffee
WHERE Price > 9.95 ORDER BY Price DESC
SELECT * FROM Coffee ORDER BY Price
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Mathematical Functions
The AVG function
calculates the average value in a particular column
The SUM function
calculates the sum of a column’s values
The MIN and MAX functions
calculate the minimum and maximum values found in a
column
The COUNT function
can be used to determine the number of rows in a table
SELECT AVG(Price) FROM Coffee
SELECT SUM(Price) FROM Coffee
SELECT MIN(Price) FROM Coffee
SELECT MAX(Price) FROM Coffee
SELECT COUNT(*) FROM Coffee
Example: CoffeeMath.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Inserting Rows
In SQL, the INSERT statement inserts a row into a
table
TableName is the name of the database table
Value1, Value2, ... is a list of column values
Example:
Strings are enclosed in single quotes
Values appear in the same order as the columns in the table
Inserts a new row with the following column values:
INSERT INTO TableName VALUES (Value1, Value2, ...)
INSERT INTO Coffee
VALUES ('Honduran Dark', '22-001', 8.65)
Description: Honduran Dark
ProdNum: 22-001
Price: 8.65
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Inserting Rows
If column order is uncertain, the following general format can
be used
ColumnName1, ColumnName2, ... is a list of column names
Value1, Value2, ... is a list of corresponding column values
Example:
Keep in mind that primary key values must be unique
For example, a duplicate ProdNum is not allowed in the Coffee
table
INSERT INTO TableName
(ColumnName1, ColumnName2, ...)
VALUES
(Value1, Value2, ...)
INSERT INTO Coffee
(ProdNum, Price, Description)
VALUES
('22-001', 8.65, 'Honduran
Dark')
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Inserting Rows with JDBC
To issue an INSERT statement, you must get a
reference to a Statement object
The Statement object has an executeUpdate method
Accepts a string containing the SQL INSERT statement as an argument
Returns an int value for the number of rows inserted
Example:
rows should contain the value 1, indicating that one row was
inserted
String sqlStatement = "INSERT INTO Coffee " +
"(ProdNum, Price, Description)" +
" VALUES " +
"('22-001', 8.65, 'Honduran Dark')";
int rows = stmt.executeUpdate(sqlStatement);
Example: CoffeeInserter.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Updating an Existing Row
In SQL, the UPDATE statement changes the contents
of an existing row in a table
Table is a table name
Column is a column name
Value is the value to store in the column
Criteria is a conditional expression
Example:
UPDATE Table
SET Column = Value
WHERE Criteria
UPDATE Coffee
SET Price = 9.95
WHERE Description = 'Galapagos Organic Medium'
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Updating More Than One Row
It is possible to update more than one row
Example:
Updates the price of all rows where the product number begins
with 21
Warning!
Because this statement does not have a WHERE clause, it will
change the price for every row
UPDATE Coffee
SET Price = 12.95
WHERE ProdNum LIKE '21%'
UPDATE Coffee
SET Price = 4.95
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Updating Rows with JDBC
To issue an UPDATE statement, you must get a
reference to a Statement object
The Statement object has an executeUpdate method
Accepts a string containing the SQL UPDATE statement as an
argument
Returns an int value for the number of rows affected
Example:
rows indicates the number of rows that were changed
String sqlStatement = "UPDATE Coffee " +
"SET Price = 9.95" +
" WHERE " +
"Description = 'Brazilian Decaf'";
int rows = stmt.executeUpdate(sqlStatement);
Example: CoffeePriceUpdater.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Deleting Rows with the
DELETE Statement
In SQL, the DELETE statement deletes one or more rows in a table
Table is the table name
Criteria is a conditional expression
Example 1:
Deletes a single row in the Coffee table where the product number is
20-001
Example 2:
Deletes all rows in the Coffee table where the description begins with
Sumatra
Warning!
– Because this statement does not have a WHERE clause, it will delete
every row in the Coffee table
DELETE FROM Table WHERE Criteria
DELETE FROM Coffee
DELETE FROM Coffee WHERE ProdNum = '20-001'
DELETE FROM Coffee WHERE Description LIKE 'Sumatra%'
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Deleting Rows with JDBC
To issue a DELETE statement, you must get a
reference to a Statement object
The Statement object has an executeUpdate method
Accepts a string containing the SQL DELETE statement as an
argument
Returns an int value for the number of rows that were deleted
Example:
rows indicates the number of rows that were deleted
String sqlStatement = "DELETE FROM Coffee " +
"WHERE ProdNum = '20-001'";
int rows = stmt.executeUpdate(sqlStatement);
Example: CoffeeDeleter.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Creating Tables with the
CREATE TABLE Statement
In SQL, the CREATE TABLE statement adds a new table to the
database
TableName is the name of the table
ColumnName1 is the name of the first column
DataType1 is the SQL data type for the first column
ColumnName2 is the name of the second column
DataType2 is the SQL data type for the second column
Example:
Creates a new table named Customer with the columns Name,
Address, City, State, and Zip
CREATE TABLE TableName
(ColumnName1 DataType1,
ColumnName2 DataType2, ...)
CREATE TABLE Customer
( Name CHAR(25), Address CHAR(25),
City CHAR(12), State CHAR(2), Zip CHAR(5) )
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Creating Tables with the
CREATE TABLE Statement
The PRIMARY KEY qualifier is used to specify a
column as the primary key
The NOT NULL qualifier is used to specify that the
column must contain a value for every row
Qualifiers should be listed after the column’s data type
Example: CreateCustomerTable.java
Creates a new table named Customer with the columns
CustomerNumber, which is the primary key, Name, Address, City,
State, and Zip
CREATE TABLE Customer
( CustomerNumber CHAR(10) NOT NULL PRIMARY KEY
Name CHAR(25), Address CHAR(25),
City CHAR(12), State CHAR(2), Zip CHAR(5) )
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Removing a Table with the
DROP TABLE Statement
In SQL, the DROP TABLE statement deletes an
existing table from the database
TableName is the name of the table you wish to delete
Example:
Deletes the Customer table from the CoffeeDB
database
Useful if you make a mistake creating a table
Simply delete the table and recreate
DROP TABLE TableName
DROP TABLE Customer
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Creating a New Database with
Java DB
The ;create=true attribute creates a new database
when appended to the database URL
Creates an empty database named EntertainmentDB
The CREATE TABLE statement can be used to create tables
Java DB creates a folder with the name of the database on your
system
Delete the database folder to delete the database
Example: BuildEntertainmentDB.java
"jdbc:derby:EntertainmentDB;create=true"
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Scrollable Result Sets
By default, a ResultSet object is created with a read-
only concurrency level and the cursor is limited to
forward movement
A scrollable result set can be created with the overloaded
version the Connection object’s createStatement
method
type is a constant for the scrolling type
concur is a constant for the concurrency level
Example:
Creates a scrollable result set that is read-only and insensitive to
database changes
conn.createStatement(type, concur);
Statement stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The ResultSet Scrolling
Types
ResultSet.TYPE_FORWARD_ONLY
Default scrolling type
Cursor moves forward only
ResultSet.TYPE_SCROLL_INSENSITIVE
Cursor moves both forward and backward
Changes made to the database do not appear
ResultSet.TYPE_SCROLL_SENSITIVE
Cursor moves both forward and backward
Changes made to the database appear as soon as they
are made
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The ResultSet Concurrency
Levels
ResultSet.CONCUR_READ_ONLY
Default concurrency level
Read-only version of data from the database
Cannot change database by altering result set
ResultSet.CONCUR_UPDATEABLE
Result set is updateable
Changes can be made to the result set and saved to the
database
Uses methods that allow changes to be made to the
database without issuing SQL statements
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
ResultSet Navigation
Methods
first()
Moves the cursor to the first row
last()
Moves the cursor to the last row
next()
Moves the cursor to the next row
previous()
Moves the cursor to the previous row
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
ResultSet Navigation
Methods
relative(rows)
Moves the cursor the number specified by the rows
argument relative to the current row
A positive rows value will move the cursor forward
A negative rows value will move the cursor backward
absolute(rows)
Moves the cursor to the row number specified by the
rows argument
A rows value of 1 will move the cursor to the first row
A rows value of 2 will move cursor to the second row
And so on until the last row
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Determining the Number of
Rows in a Result Set
ResultSet navigation methods can be used
to determine the number of rows in a result
set
Example:
Move cursor to last row
Get the last row’s number and store the value
Move back to the first row
resultSet.last() // Move to the last row
int numRows = resultSet.getRow(); // Get the current row number
resultSet.first(); // Move back to the first row
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Result Set Metadata
Metadata refers to data that describes other data
A ResultSet object has metadata that describes a
result set
Can be used to determine many things about a result
set
Number of columns
Column names
Column data types
And much more
Useful for submitting SQL queries in applications
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Result Set Metadata
• ResultSetMetaData is an interface in the
java.sql package
The getMetaData method of a ResultSet
object returns a reference to a
ResultSetMetaData object.
Example: MetaDataDemo.java
Creates a ResultSetMetaData object reference
variable named meta
ResultSetMetaData meta = resultSet.getMetaData();
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
A Few ResultSetMetaData Methods
Method Description
int getColumnCount() Returns the number of columns in the result set.
String getColumnName(int col) Returns the name of the column specified by the
integer col. The first column is column 1.
String getColumnTypeName(int col) Returns the name of the data type of the column
specified by the integer col. The first column is
column 1. The data type name returned is the
database-specific SQL data type.
int getColumnDisplaySize(int col) Returns the display width, in characters, of the
column specified by the integer col. The first
column is column 1.
String getTableName(int col) Returns the name of the table associated with the
column specified by the integer col. The first
column is column 1.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The JTable Class
The JTable class is a Swing component that
displays data in a two-dimensional table
rowData is a two-dimensional array of objects
Contains data that will be displayed in the table
Each row becomes a row of data in the table
Each column becomes a column of data in the table
JTable calls toString method of each object to get values
colNames is a one-dimensional array of objects
Contains the column names to display
JTable calls toString method of each object to get value
Jtable(Object[][] rowData, Object[] colNames)
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Setting Up a Simple JTable
Component
Example:
The figure shows an example of how the table appears in a
frame
String[] colNames = {"Name", "Telephone" };
String[][] rowData = {{ "Jean", "555-2222" },
{ "Tim", "555-1212" },
{ "Matt", "555-9999" },
{ "Rose", "555-4545" },
{ "Geri", "555-5214" },
{ "Shawn", "555-7821" },
{ "Renee", "555-9640" },
{ "Joe", "555-8657" } };
JTable myTable = new JTable(rowData, colNames);
JScrollPane scrollPane = new JScrollPane(JTable);
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Displaying Query Results in a
JTable
Example: TableFormatter.java, CoffeeDBQuery.java, CoffeeDBViewer.java
This window
appears first
The user enters a
SELECT statement
and clicks the
Submit button This window
appears next
It displays the
results in a Jtable
component
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Relational Data
A foreign key is a column in one table that
references a primary key in another table
Creates a relationship between the tables
Example:
The CustomerNumber column references the Customer table
The ProdNum column references the Coffee table
This creates a relationship between the tables of the CoffeeDB
database
UnpaidOrder table:
CustomerNumber CHAR(10) Foreign Key
ProdNum CHAR(10) Foreign Key
OrderDate CHAR(10)
Quantity DOUBLE
Cost DOUBLE
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Creating the UnpaidOrder
Table
The following SQL statement creates the UnpaidOrder table in
the CoffeeDB database:
The REFERENCES qualifier ensures referential integrity between
tables
The CustomerNumber in the UnpaidOrder table must contain a valid
CustomerNumber from the Customer table
The ProdNum in the UnpaidOrder table must contain a valid ProdNum
from the Coffee table
CREATE TABLE UnpaidOrder
( CustomerNumber CHAR(10) NOT NULL
REFERENCES Customer(CustomerNumber),
ProdNum CHAR(10) NOT NULL
REFERENCES Coffee(ProdNum),
OrderDate CHAR(10),
Quantity DOUBLE,
Cost DOUBLE )
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Entity Relationship Diagrams
An entity relationship diagram shows the relationships
between tables
Primary keys are denoted with (PK)
Lines drawn between tables show how they are related
The ends of each line show either a 1 or an infinity symbol (∞)
The infinity symbol means many and number 1 means one.
A one to many relationship means that for each row in table A there can
be many rows in table B that reference it.
A many to one relationship means that many rows in table A can
reference a single row in table B.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
CoffeeDB Relationships Left
to Right
One to many relationship between Customer and UnpaidOrder
One row in the Customer table may be referenced by many
rows in the UnpaidOrder table
Many to one relationship between the UnpaidOrder and
Coffee tables
Many rows in the UnpaidOrder table may reference a single
row in the Coffee table.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
CoffeeDB Relationships
Right to Left
One to many relationship between Coffee and UnpaidOrder
One row in the Coffee table may be referenced by many rows
in the UnpaidOrder table
Many to one relationship between UnpaidOrder and Customer
Many rows in the UnpaidOrder table may reference a single
row in the Customer table.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Joining Data from Multiple
Tables
In SQL, you must use qualified column names in a SELECT statement if
the tables have columns with the same name
A qualified column name takes the following form:
Example:
The search criteria tell the DBMS how to link the rows in the tables
TableName.ColumnName
SELECT
Customer.CustomerNumber, Customer.Name,
UnpaidOrder.OrderDate, UnpaidOrder.Cost,
Coffee.Description
FROM
Customer, UnpaidOrder, Coffee
WHERE
UnpaidOrder.CustomerNumber = Customer.CustomerNumber
AND
UnpaidOrder.ProdNum = Coffee.ProdNum
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
An Order Entry System
The Place Order application uses a relational database
(CoffeeDB)
Requires the Coffee, Customer, and UnpaidOrder tables
Example: CoffeeDBManager.java, CustomerPanel.java,
CoffeePanel.java, QtyDatePanel.java,
PlaceOrder.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Transactions
An operation that requires multiple database updates is known
as a transaction.
For a transaction to be complete
All of the steps involved in the transaction must be performed.
If any single step within a transaction fails
None of the steps in the transaction should be performed.
When you write transaction-processing code, there are two
concepts you must understand:
Commit
Rollback
The term commit refers to making a permanent change to a
database
The term rollback refers to undoing changes to a database
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
JDBC Auto Commit Mode
By default, the JDBC Connection class operates in
auto commit mode.
In auto commit mode
All updates that are made to the database are made
permanent as soon as they are executed.
When auto commit mode is turned off
Changes do not become permanent until a commit
command is executed
A rollback command can be used to undo changes
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
JDBC Transaction Methods
To turn auto commit mode off
Call the Connection class's setAutoCommit method
Pass the argument false
To execute a commit command
Call the Connection class's commit method
To execute a rollback command
Call the Connection class's
conn.setAutoCommit(false);
conn.commit();
conn.rollback();
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
JDBC Transaction Example
conn.setAutoCommit(false);
// Attempt the transaction
try
{
// Update the inventory records.
stmt.executeUpdate(updateStatement);
// Add the order to the UnpaidOrder table.
stmt.executeUpdate(insertStatement);
// Commit all these updates.
conn.commit();
}
catch (SQLException ex)
{
// Roll back the changes.
conn.rollback();
}
The commit
method is called
in the try block
The rollback
method is called
in the catch block
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Stored Procedures
Many commercial database systems allow you to create SQL
statements and store them in the DBMS itself
These SQL statements are called stored procedures
Can be executed by other applications using the DBMS
Ideal for SQL statements that are used often in a variety of applications
Usually execute faster than SQL statements that are submitted from
applications outside the DBMS
Each DBMS has its own syntax for creating a stored procedure
in SQL
To execute a stored procedure, you must create a
CallableStatement object
CallableStatement is an interface in the java.sql package
To create a CallableStatement object, you call the
Connection class's prepareCall statement

More Related Content

What's hot

DEE 431 Introduction to Mysql Slide 3
DEE 431 Introduction to Mysql Slide 3DEE 431 Introduction to Mysql Slide 3
DEE 431 Introduction to Mysql Slide 3YOGESH SINGH
 
Athena java dev guide
Athena java dev guideAthena java dev guide
Athena java dev guidedvdung
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity DevAdnani
 
Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句renguzi
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeClay Helberg
 
AvocadoDB query language (DRAFT!)
AvocadoDB query language (DRAFT!)AvocadoDB query language (DRAFT!)
AvocadoDB query language (DRAFT!)avocadodb
 
Parsing strange v3
Parsing strange v3Parsing strange v3
Parsing strange v3Hal Stern
 
OData Introduction and Impact on API Design (Webcast)
OData Introduction and Impact on API Design (Webcast)OData Introduction and Impact on API Design (Webcast)
OData Introduction and Impact on API Design (Webcast)Apigee | Google Cloud
 
Generating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data ModelerGenerating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data ModelerRob van den Berg
 
Sql a practical introduction
Sql   a practical introductionSql   a practical introduction
Sql a practical introductionHasan Kata
 
What is SQL Server?
What is SQL Server?What is SQL Server?
What is SQL Server?CPD INDIA
 
Parsing strange v2
Parsing strange v2Parsing strange v2
Parsing strange v2Hal Stern
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaEdureka!
 
LeverX SAP Essential Tutorial - Simple Data Extraction
LeverX SAP Essential Tutorial - Simple Data ExtractionLeverX SAP Essential Tutorial - Simple Data Extraction
LeverX SAP Essential Tutorial - Simple Data ExtractionLeverX
 

What's hot (20)

DEE 431 Introduction to Mysql Slide 3
DEE 431 Introduction to Mysql Slide 3DEE 431 Introduction to Mysql Slide 3
DEE 431 Introduction to Mysql Slide 3
 
Athena java dev guide
Athena java dev guideAthena java dev guide
Athena java dev guide
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity
 
Practical OData
Practical ODataPractical OData
Practical OData
 
Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句
 
Oracle SQLcl
Oracle SQLcl Oracle SQLcl
Oracle SQLcl
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data Merge
 
AvocadoDB query language (DRAFT!)
AvocadoDB query language (DRAFT!)AvocadoDB query language (DRAFT!)
AvocadoDB query language (DRAFT!)
 
Parsing strange v3
Parsing strange v3Parsing strange v3
Parsing strange v3
 
OData Introduction and Impact on API Design (Webcast)
OData Introduction and Impact on API Design (Webcast)OData Introduction and Impact on API Design (Webcast)
OData Introduction and Impact on API Design (Webcast)
 
Generating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data ModelerGenerating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data Modeler
 
Ebook2
Ebook2Ebook2
Ebook2
 
81 Rac
81 Rac81 Rac
81 Rac
 
Sql a practical introduction
Sql   a practical introductionSql   a practical introduction
Sql a practical introduction
 
What is SQL Server?
What is SQL Server?What is SQL Server?
What is SQL Server?
 
Parsing strange v2
Parsing strange v2Parsing strange v2
Parsing strange v2
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
 
LeverX SAP Essential Tutorial - Simple Data Extraction
LeverX SAP Essential Tutorial - Simple Data ExtractionLeverX SAP Essential Tutorial - Simple Data Extraction
LeverX SAP Essential Tutorial - Simple Data Extraction
 
SQL overview and software
SQL overview and softwareSQL overview and software
SQL overview and software
 

Viewers also liked

Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eGina Bullock
 
Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eGina Bullock
 
Dubai attestation
Dubai attestationDubai attestation
Dubai attestationcenturygulf
 
Tour de yorkshire 2
Tour de yorkshire 2Tour de yorkshire 2
Tour de yorkshire 2Alex Almond
 
Taking control of your law firm's web presence
Taking control of your law firm's web presenceTaking control of your law firm's web presence
Taking control of your law firm's web presenceDan Jaffe
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eGina Bullock
 
Radiación y Propagacion
Radiación y PropagacionRadiación y Propagacion
Radiación y Propagacionmichael howard
 
Planeaciones jornada dos
Planeaciones jornada dosPlaneaciones jornada dos
Planeaciones jornada dosMonserrat Soto
 
Maxus FIFA Tracker - Day 10 - 21 June'14
Maxus FIFA Tracker - Day 10 - 21 June'14Maxus FIFA Tracker - Day 10 - 21 June'14
Maxus FIFA Tracker - Day 10 - 21 June'14MaxusIndia
 
Biz Social Media Snow Camp 2015 - Laurentiu Dumitrescu
Biz Social Media Snow Camp 2015 - Laurentiu DumitrescuBiz Social Media Snow Camp 2015 - Laurentiu Dumitrescu
Biz Social Media Snow Camp 2015 - Laurentiu DumitrescuGabriel Barliga
 
RUBRICAS PRIMERA JORNADA
RUBRICAS PRIMERA JORNADARUBRICAS PRIMERA JORNADA
RUBRICAS PRIMERA JORNADAMonserrat Soto
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eGina Bullock
 
Shooting Schedule and Equipment List
Shooting Schedule and Equipment ListShooting Schedule and Equipment List
Shooting Schedule and Equipment ListDeclan556
 
The Best Estate Agent marketing ideas 2015 (so far)
The Best Estate Agent marketing ideas 2015 (so far)The Best Estate Agent marketing ideas 2015 (so far)
The Best Estate Agent marketing ideas 2015 (so far)Sam Ashdown
 
Preliminary Risk Assessment
Preliminary Risk AssessmentPreliminary Risk Assessment
Preliminary Risk AssessmentDeclan556
 

Viewers also liked (20)

Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5e
 
Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5e
 
Dubai attestation
Dubai attestationDubai attestation
Dubai attestation
 
Cartilla fenicia comercial
Cartilla fenicia comercialCartilla fenicia comercial
Cartilla fenicia comercial
 
Tour de yorkshire 2
Tour de yorkshire 2Tour de yorkshire 2
Tour de yorkshire 2
 
document-15
document-15document-15
document-15
 
Taking control of your law firm's web presence
Taking control of your law firm's web presenceTaking control of your law firm's web presence
Taking control of your law firm's web presence
 
Exposición #2
Exposición #2Exposición #2
Exposición #2
 
SAPS QUÈ?Exprés FITOSANITARIS
SAPS QUÈ?Exprés FITOSANITARISSAPS QUÈ?Exprés FITOSANITARIS
SAPS QUÈ?Exprés FITOSANITARIS
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5e
 
Jonathan Drum Resume
Jonathan Drum ResumeJonathan Drum Resume
Jonathan Drum Resume
 
Radiación y Propagacion
Radiación y PropagacionRadiación y Propagacion
Radiación y Propagacion
 
Planeaciones jornada dos
Planeaciones jornada dosPlaneaciones jornada dos
Planeaciones jornada dos
 
Maxus FIFA Tracker - Day 10 - 21 June'14
Maxus FIFA Tracker - Day 10 - 21 June'14Maxus FIFA Tracker - Day 10 - 21 June'14
Maxus FIFA Tracker - Day 10 - 21 June'14
 
Biz Social Media Snow Camp 2015 - Laurentiu Dumitrescu
Biz Social Media Snow Camp 2015 - Laurentiu DumitrescuBiz Social Media Snow Camp 2015 - Laurentiu Dumitrescu
Biz Social Media Snow Camp 2015 - Laurentiu Dumitrescu
 
RUBRICAS PRIMERA JORNADA
RUBRICAS PRIMERA JORNADARUBRICAS PRIMERA JORNADA
RUBRICAS PRIMERA JORNADA
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5e
 
Shooting Schedule and Equipment List
Shooting Schedule and Equipment ListShooting Schedule and Equipment List
Shooting Schedule and Equipment List
 
The Best Estate Agent marketing ideas 2015 (so far)
The Best Estate Agent marketing ideas 2015 (so far)The Best Estate Agent marketing ideas 2015 (so far)
The Best Estate Agent marketing ideas 2015 (so far)
 
Preliminary Risk Assessment
Preliminary Risk AssessmentPreliminary Risk Assessment
Preliminary Risk Assessment
 

Similar to Database Chapter Overview (20)

Jdbc
JdbcJdbc
Jdbc
 
Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
 
PPT temp.pptx
PPT temp.pptxPPT temp.pptx
PPT temp.pptx
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Lecture13
Lecture13Lecture13
Lecture13
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Lecture12
Lecture12Lecture12
Lecture12
 
Jdbc
JdbcJdbc
Jdbc
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
Mule jdbc
Mule   jdbcMule   jdbc
Mule jdbc
 
Is2215 lecture7 lecturer_ado_intro
Is2215 lecture7 lecturer_ado_introIs2215 lecture7 lecturer_ado_intro
Is2215 lecture7 lecturer_ado_intro
 
Databases
DatabasesDatabases
Databases
 
Ef code first
Ef code firstEf code first
Ef code first
 
CS 542 Introduction
CS 542 IntroductionCS 542 Introduction
CS 542 Introduction
 
Intro
IntroIntro
Intro
 
Introduction to Oracle
Introduction to OracleIntroduction to Oracle
Introduction to Oracle
 
Introduction to Oracle
Introduction to OracleIntroduction to Oracle
Introduction to Oracle
 
hoffer_edm_pp_ch06.ppt
hoffer_edm_pp_ch06.ppthoffer_edm_pp_ch06.ppt
hoffer_edm_pp_ch06.ppt
 
hoffer_edm_pp_ch06.ppt
hoffer_edm_pp_ch06.ppthoffer_edm_pp_ch06.ppt
hoffer_edm_pp_ch06.ppt
 
SQLPpt.ppt
SQLPpt.pptSQLPpt.ppt
SQLPpt.ppt
 

More from Gina Bullock

Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eGina Bullock
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eGina Bullock
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eGina Bullock
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eGina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eGina Bullock
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eGina Bullock
 
Eo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eEo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eGina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eGina Bullock
 
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eGina Bullock
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eGina Bullock
 
Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eGina Bullock
 
Eo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5eEo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5eGina Bullock
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eGina Bullock
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eGina Bullock
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eGina Bullock
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eGina Bullock
 
Eo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5eEo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5eGina Bullock
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eGina Bullock
 
Eo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eEo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eGina Bullock
 
Eo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eEo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eGina Bullock
 

More from Gina Bullock (20)

Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5e
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5e
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5e
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5e
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5e
 
Eo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eEo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5e
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5e
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5e
 
Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5e
 
Eo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5eEo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5e
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5e
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5e
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5e
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5e
 
Eo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5eEo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5e
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5e
 
Eo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eEo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5e
 
Eo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eEo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5e
 

Recently uploaded

HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 

Recently uploaded (20)

HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 

Database Chapter Overview

  • 1. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C HA PT E R 16 Databases
  • 2. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics Introduction to Database Management Systems Tables, Rows, and Columns Introduction to the SQL SELECT Statement Inserting Rows Updating and Deleting Existing Rows Creating and Deleting Tables
  • 3. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics Creating a New Database with JDBC Scrollable Result Sets Result Set Meta Data Displaying Query Results in a Jtable Relational Data Advanced Topics
  • 4. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to Database Management Systems Storing data in traditional text or binary files has its limits well suited for applications that store only a small amount of data not practical for applications that must store a large amount of data simple operations become cumbersome and inefficient as data increases
  • 5. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to Database Management Systems A database management system (DBMS) is software that is specifically designed to work with large amounts of data in an efficient and organized manner Data is stored using the database management system Applications written in Java or other languages communicate with the DBMS rather than manipulate the data directly DBMS carries out instructions and sends the results back to the application
  • 6. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Application sends a command to the DBMS The DBMS executes the command on the Data The Application displays the result to the user The DBMS sends the result back to the Application Introduction to Database Management Systems
  • 7. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley JDBC JDBC stands for Java database connectivity It is the technology that makes communication possible between the Java application and DBMS The Java API contains numerous JDBC classes that allow your Java applications to interact with a DBMS
  • 8. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley SQL SQL stands for structured query language A standard language for working with database management systems Not used as a general programming language Consists of several key words, used to construct statements known as queries Statements or queries are strings passed from the application to the DBMS using API method calls Serve as instructions for the DBMS to carry out operations on its data
  • 9. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using a DBMS To use JDBC to work with a database you will need a DBMS Oracle Microsoft SQL Server DB2 MySQL Java DB The examples in this chapter were created with Java DB
  • 10. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java DB Java DB is an open source distribution of Apache Derby, a pure Java DBMS that is made freely available from Oracle. It is designed specifically for Java applications and is easy to install and use. All of the examples in this chapter were created with Java DB.
  • 11. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Creating the CoffeeDB Database In this chapter we will use a database named CoffeeDB as our example. After you have installed the Java DB DBMS, perform the following steps to create the CoffeeDB database: Make sure you have downloaded Student Source Code files from the book's companion Web site. In this chapter's source code files, locate a program named CreateCoffeeDB.java. Compile and execute the CreateCoffeeDB.java program. If Java DB is properly installed, this program will create the CoffeeDB database on your system.
  • 12. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Connecting to the CoffeeDB Database The static DriverManager.getConnection method is used to get a connection to the database General format of the simplest version: General format if a user name and a password are required: Username is a string containing a valid username Password is a string containing a password DatabaseURL lists the protocol used to access the database DriverManager.getConnection(DatabaseURL); DriverManager.getConnection(DatabaseURL, Username, Password);
  • 13. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Connecting to the CoffeeDB Database DatabaseURL is a string known as a database URL URL stands for uniform resource locator A simple database URL has the following general format: protocol is the database protocol value is jdbc when using JDBC subprotocol varies depending on the type of DBMS value is derby when using Java DB databaseName is the name of the database Using Java DB, the URL for the CoffeeDB database is: protocol:subprotocol:databaseName jdbc:derby:CoffeeDB
  • 14. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Connecting to the CoffeeDB Database The DriverManager.getConnection method Searches for and loads a compatible JDBC driver for the database specified by the URL Returns a reference to a Connection object Should be saved in a variable, so it can be used later (more on this in a moment) Throws an SQLException if it fails to load a compatible JDBC driver Example: TestConnection.java Final String DB_URL = "jdbc:derby:CoffeeDB"; Connection conn = DriverManager.getConnection(DB_URL);
  • 15. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Tables, Rows, and Columns A database management system stores data in a database A database is organized into one or more tables Each table holds a collection of related data, organized into rows and columns A row is a complete set of information about a single item, divided into columns Each column is an individual piece of information about the item
  • 16. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Database Organization
  • 17. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Coffee database table Each row contains data for a single item.
  • 18. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Column Data Types • Columns in a database are assigned an SQL data type – SQL data types are generally compatible with Java data types
  • 19. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Coffee Table Column Data Types Description column data type is CHAR(25) String with a fixed length of 25 characters Compatible with the String type in Java ProdNum column data type is CHAR(10) String with a fixed length of 10 characters Compatible with the String type in Java Price column data type is DOUBLE Double-precision floating-point number Compatible with the double data type in Java
  • 20. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Primary Keys A primary key is a column that holds a unique value for each row in a database table In the Coffee table, ProdNum is the primary key Each type of coffee has a unique product number Used to identify any coffee stored in the table A primary key can be the combination of several columns in a table
  • 21. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The SQL SELECT Statement The SELECT statement is used to retrieve the rows in a table Columns is one or more column names Table is a table name Example 1: Example 2: Multiple column names are separated with a comma Example 3: The * character can be used to retrieve all columns in the table SELECT Columns FROM Table SELECT Description FROM Coffee SELECT Description, Price FROM Coffee SELECT * FROM Coffee
  • 22. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley More About SQL Statements • SQL statements are free form – tabs, new lines, and spaces between key words are ignored • SQL key words and table names are case insensitive • Example: SELECT * FROM Coffee SELECT * FROM Coffee select * from coffee The following statements all work the same:
  • 23. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Passing an SQL Statement to the DBMS Once you have established a connection, you must get a reference to a Statement object before you can issue SQL statements to the DBMS A Statement object has an executeQuery method that returns a reference to a ResultSet object A ResultSet object contains the results of the query Example: Connection conn = DriverManager.getConnection(DB_URL); Statement stmt = conn.createStatement(); String sqlStatement = "SELECT Description FROM Coffee"; ResultSet result = stmt.executeQuery(sqlStatement);
  • 24. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Getting a Row from the ResultSet Object A ResultSet object has an internal cursor Points to a specific row in the ResultSet The row to which it points is the current row Initially positioned just before the first row Can be moved from row to row to examine all rows
  • 25. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Getting a Row from the ResultSet Object A ResultSet object’s next method moves the cursor to the next row in the ResultSet moves to first row in a newly created ResultSet moves to the next row each time it is called result.next();
  • 26. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Getting a Row from the ResultSet Object A ResultSet object’s next method returns a Boolean value true if successfully moved to the next row false if there are no more rows A while loop can be used to move through all the rows of a newly created ResultSet while (result.next()) { // Process the current row. }
  • 27. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Getting Columns in a ResultSet Object You use one of the ResultSet object’s “get” methods to retrieve the contents of a specific column in the current row. Can pass an argument for either the column number or the column name System.out.println(result.getString(1)); System.out.println(result.getString(1)); System.out.println(result.getString(1)); System.out.println(result.getString("Description")); System.out.println(result.getString("ProdNum")); System.out.println(result.getDouble("Price")); Examples: ShowCoffeeDescriptions.java ShowDescriptionsAndPrices.java
  • 28. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Getting Columns in a ResultSet Object ResultSet Method Description double getDouble(int colNumber) double getDouble(String colName) Returns the double that is stored in the column specified by colNumber or colName. The column must hold data that is compatible with the double data type in Java. If an error occurs, the method throws an SQLException. int getInt(int colNumber) int getInt(String colName) Returns the int that is stored in the column specified by colNumber or colName. The column must hold data that is compatible with the int data type in Java. If an error occurs, the method throws an SQLException. String getString(int colNumber) String getString(String colName) Returns the string that is stored in the column specified by colNumber or colName. The column must hold data that is compatible with the String type in Java. If an error occurs, the method throws an SQLException.
  • 29. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Specifying Search Criteria with the WHERE clause The WHERE clause can be used with the SELECT statement to specify a search criteria Criteria is a conditional expression Example: Only the rows that meet the search criteria are returned in the result set A result set is an object that contains the results of an SQL statement SELECT Columns FROM Table WHERE Criteria SELECT * FROM Coffee WHERE Price > 12.00
  • 30. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley SQL Relational Operators Standard SQL supports the following relational operators: Notice a few SQL relational operators are different than in Java SQL equal to operator is = SQL not equal to operator is <> Example: CoffeeMinPrice.java Operator Meaning > Greater than < Less than >= Greater than or equal to <= Less than or equal to = Equal to <> Not equal to
  • 31. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley String Comparisons in SQL Example 1: In SQL, strings are enclosed in single quotes Warning! String comparisons in SQL are case sensitive Example 2: The UPPER() or LOWER() functions convert the string to uppercase or lowercase and can help prevent case sensitive errors when comparing strings Example 3: If a single quote (') is part of a string, use two single quotes ('') SELECT * FROM Coffee WHERE Description ='Joe''s Special Blend' SELECT * FROM Coffee WHERE UPPER(Description) = 'FRENCH ROAST DARK' SELECT * FROM Coffee WHERE Description = 'french roast dark' SELECT * FROM Coffee WHERE Description = 'French Roast Dark'
  • 32. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using the LIKE Operator In SQL, the LIKE operator can be used to search for a substring Example 1: The % symbol is used as a wildcard for multiple characters Example 2: The underscore (_) is a used as a wildcard for a single character Example 3: The NOT operator is used to disqualify the search criteria SELECT * FROM Coffee WHERE Description LIKE '%Decaf%' SELECT * FROM Coffee WHERE ProdNum LIKE '2_-00_' SELECT * FROM Coffee WHERE Description NOT LIKE '%Decaf%'
  • 33. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using AND and OR The AND and OR operators can be used to specify multiple search criteria in a WHERE clause Example 1: The AND operator requires that both search criteria be true Example 2: The OR operator requires that either search criteria be true SELECT * FROM Coffee WHERE Price > 10.00 AND Price < 14.00 SELECT * FROM Coffee WHERE Description LIKE '%Dark%' OR ProdNum LIKE '16%'
  • 34. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Sorting the Results of a SELECT Query Use the ORDER BY clause to sort results according to a column value Example 1: Sorted in ascending order (ASC) by default Example 2: Use the DESC operator to sort results in descending order SELECT * FROM Coffee WHERE Price > 9.95 ORDER BY Price DESC SELECT * FROM Coffee ORDER BY Price
  • 35. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Mathematical Functions The AVG function calculates the average value in a particular column The SUM function calculates the sum of a column’s values The MIN and MAX functions calculate the minimum and maximum values found in a column The COUNT function can be used to determine the number of rows in a table SELECT AVG(Price) FROM Coffee SELECT SUM(Price) FROM Coffee SELECT MIN(Price) FROM Coffee SELECT MAX(Price) FROM Coffee SELECT COUNT(*) FROM Coffee Example: CoffeeMath.java
  • 36. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Inserting Rows In SQL, the INSERT statement inserts a row into a table TableName is the name of the database table Value1, Value2, ... is a list of column values Example: Strings are enclosed in single quotes Values appear in the same order as the columns in the table Inserts a new row with the following column values: INSERT INTO TableName VALUES (Value1, Value2, ...) INSERT INTO Coffee VALUES ('Honduran Dark', '22-001', 8.65) Description: Honduran Dark ProdNum: 22-001 Price: 8.65
  • 37. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Inserting Rows If column order is uncertain, the following general format can be used ColumnName1, ColumnName2, ... is a list of column names Value1, Value2, ... is a list of corresponding column values Example: Keep in mind that primary key values must be unique For example, a duplicate ProdNum is not allowed in the Coffee table INSERT INTO TableName (ColumnName1, ColumnName2, ...) VALUES (Value1, Value2, ...) INSERT INTO Coffee (ProdNum, Price, Description) VALUES ('22-001', 8.65, 'Honduran Dark')
  • 38. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Inserting Rows with JDBC To issue an INSERT statement, you must get a reference to a Statement object The Statement object has an executeUpdate method Accepts a string containing the SQL INSERT statement as an argument Returns an int value for the number of rows inserted Example: rows should contain the value 1, indicating that one row was inserted String sqlStatement = "INSERT INTO Coffee " + "(ProdNum, Price, Description)" + " VALUES " + "('22-001', 8.65, 'Honduran Dark')"; int rows = stmt.executeUpdate(sqlStatement); Example: CoffeeInserter.java
  • 39. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Updating an Existing Row In SQL, the UPDATE statement changes the contents of an existing row in a table Table is a table name Column is a column name Value is the value to store in the column Criteria is a conditional expression Example: UPDATE Table SET Column = Value WHERE Criteria UPDATE Coffee SET Price = 9.95 WHERE Description = 'Galapagos Organic Medium'
  • 40. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Updating More Than One Row It is possible to update more than one row Example: Updates the price of all rows where the product number begins with 21 Warning! Because this statement does not have a WHERE clause, it will change the price for every row UPDATE Coffee SET Price = 12.95 WHERE ProdNum LIKE '21%' UPDATE Coffee SET Price = 4.95
  • 41. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Updating Rows with JDBC To issue an UPDATE statement, you must get a reference to a Statement object The Statement object has an executeUpdate method Accepts a string containing the SQL UPDATE statement as an argument Returns an int value for the number of rows affected Example: rows indicates the number of rows that were changed String sqlStatement = "UPDATE Coffee " + "SET Price = 9.95" + " WHERE " + "Description = 'Brazilian Decaf'"; int rows = stmt.executeUpdate(sqlStatement); Example: CoffeePriceUpdater.java
  • 42. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Deleting Rows with the DELETE Statement In SQL, the DELETE statement deletes one or more rows in a table Table is the table name Criteria is a conditional expression Example 1: Deletes a single row in the Coffee table where the product number is 20-001 Example 2: Deletes all rows in the Coffee table where the description begins with Sumatra Warning! – Because this statement does not have a WHERE clause, it will delete every row in the Coffee table DELETE FROM Table WHERE Criteria DELETE FROM Coffee DELETE FROM Coffee WHERE ProdNum = '20-001' DELETE FROM Coffee WHERE Description LIKE 'Sumatra%'
  • 43. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Deleting Rows with JDBC To issue a DELETE statement, you must get a reference to a Statement object The Statement object has an executeUpdate method Accepts a string containing the SQL DELETE statement as an argument Returns an int value for the number of rows that were deleted Example: rows indicates the number of rows that were deleted String sqlStatement = "DELETE FROM Coffee " + "WHERE ProdNum = '20-001'"; int rows = stmt.executeUpdate(sqlStatement); Example: CoffeeDeleter.java
  • 44. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Creating Tables with the CREATE TABLE Statement In SQL, the CREATE TABLE statement adds a new table to the database TableName is the name of the table ColumnName1 is the name of the first column DataType1 is the SQL data type for the first column ColumnName2 is the name of the second column DataType2 is the SQL data type for the second column Example: Creates a new table named Customer with the columns Name, Address, City, State, and Zip CREATE TABLE TableName (ColumnName1 DataType1, ColumnName2 DataType2, ...) CREATE TABLE Customer ( Name CHAR(25), Address CHAR(25), City CHAR(12), State CHAR(2), Zip CHAR(5) )
  • 45. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Creating Tables with the CREATE TABLE Statement The PRIMARY KEY qualifier is used to specify a column as the primary key The NOT NULL qualifier is used to specify that the column must contain a value for every row Qualifiers should be listed after the column’s data type Example: CreateCustomerTable.java Creates a new table named Customer with the columns CustomerNumber, which is the primary key, Name, Address, City, State, and Zip CREATE TABLE Customer ( CustomerNumber CHAR(10) NOT NULL PRIMARY KEY Name CHAR(25), Address CHAR(25), City CHAR(12), State CHAR(2), Zip CHAR(5) )
  • 46. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Removing a Table with the DROP TABLE Statement In SQL, the DROP TABLE statement deletes an existing table from the database TableName is the name of the table you wish to delete Example: Deletes the Customer table from the CoffeeDB database Useful if you make a mistake creating a table Simply delete the table and recreate DROP TABLE TableName DROP TABLE Customer
  • 47. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Creating a New Database with Java DB The ;create=true attribute creates a new database when appended to the database URL Creates an empty database named EntertainmentDB The CREATE TABLE statement can be used to create tables Java DB creates a folder with the name of the database on your system Delete the database folder to delete the database Example: BuildEntertainmentDB.java "jdbc:derby:EntertainmentDB;create=true"
  • 48. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Scrollable Result Sets By default, a ResultSet object is created with a read- only concurrency level and the cursor is limited to forward movement A scrollable result set can be created with the overloaded version the Connection object’s createStatement method type is a constant for the scrolling type concur is a constant for the concurrency level Example: Creates a scrollable result set that is read-only and insensitive to database changes conn.createStatement(type, concur); Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
  • 49. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The ResultSet Scrolling Types ResultSet.TYPE_FORWARD_ONLY Default scrolling type Cursor moves forward only ResultSet.TYPE_SCROLL_INSENSITIVE Cursor moves both forward and backward Changes made to the database do not appear ResultSet.TYPE_SCROLL_SENSITIVE Cursor moves both forward and backward Changes made to the database appear as soon as they are made
  • 50. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The ResultSet Concurrency Levels ResultSet.CONCUR_READ_ONLY Default concurrency level Read-only version of data from the database Cannot change database by altering result set ResultSet.CONCUR_UPDATEABLE Result set is updateable Changes can be made to the result set and saved to the database Uses methods that allow changes to be made to the database without issuing SQL statements
  • 51. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley ResultSet Navigation Methods first() Moves the cursor to the first row last() Moves the cursor to the last row next() Moves the cursor to the next row previous() Moves the cursor to the previous row
  • 52. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley ResultSet Navigation Methods relative(rows) Moves the cursor the number specified by the rows argument relative to the current row A positive rows value will move the cursor forward A negative rows value will move the cursor backward absolute(rows) Moves the cursor to the row number specified by the rows argument A rows value of 1 will move the cursor to the first row A rows value of 2 will move cursor to the second row And so on until the last row
  • 53. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Determining the Number of Rows in a Result Set ResultSet navigation methods can be used to determine the number of rows in a result set Example: Move cursor to last row Get the last row’s number and store the value Move back to the first row resultSet.last() // Move to the last row int numRows = resultSet.getRow(); // Get the current row number resultSet.first(); // Move back to the first row
  • 54. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Result Set Metadata Metadata refers to data that describes other data A ResultSet object has metadata that describes a result set Can be used to determine many things about a result set Number of columns Column names Column data types And much more Useful for submitting SQL queries in applications
  • 55. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Result Set Metadata • ResultSetMetaData is an interface in the java.sql package The getMetaData method of a ResultSet object returns a reference to a ResultSetMetaData object. Example: MetaDataDemo.java Creates a ResultSetMetaData object reference variable named meta ResultSetMetaData meta = resultSet.getMetaData();
  • 56. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A Few ResultSetMetaData Methods Method Description int getColumnCount() Returns the number of columns in the result set. String getColumnName(int col) Returns the name of the column specified by the integer col. The first column is column 1. String getColumnTypeName(int col) Returns the name of the data type of the column specified by the integer col. The first column is column 1. The data type name returned is the database-specific SQL data type. int getColumnDisplaySize(int col) Returns the display width, in characters, of the column specified by the integer col. The first column is column 1. String getTableName(int col) Returns the name of the table associated with the column specified by the integer col. The first column is column 1.
  • 57. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The JTable Class The JTable class is a Swing component that displays data in a two-dimensional table rowData is a two-dimensional array of objects Contains data that will be displayed in the table Each row becomes a row of data in the table Each column becomes a column of data in the table JTable calls toString method of each object to get values colNames is a one-dimensional array of objects Contains the column names to display JTable calls toString method of each object to get value Jtable(Object[][] rowData, Object[] colNames)
  • 58. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Setting Up a Simple JTable Component Example: The figure shows an example of how the table appears in a frame String[] colNames = {"Name", "Telephone" }; String[][] rowData = {{ "Jean", "555-2222" }, { "Tim", "555-1212" }, { "Matt", "555-9999" }, { "Rose", "555-4545" }, { "Geri", "555-5214" }, { "Shawn", "555-7821" }, { "Renee", "555-9640" }, { "Joe", "555-8657" } }; JTable myTable = new JTable(rowData, colNames); JScrollPane scrollPane = new JScrollPane(JTable);
  • 59. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Displaying Query Results in a JTable Example: TableFormatter.java, CoffeeDBQuery.java, CoffeeDBViewer.java This window appears first The user enters a SELECT statement and clicks the Submit button This window appears next It displays the results in a Jtable component
  • 60. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Relational Data A foreign key is a column in one table that references a primary key in another table Creates a relationship between the tables Example: The CustomerNumber column references the Customer table The ProdNum column references the Coffee table This creates a relationship between the tables of the CoffeeDB database UnpaidOrder table: CustomerNumber CHAR(10) Foreign Key ProdNum CHAR(10) Foreign Key OrderDate CHAR(10) Quantity DOUBLE Cost DOUBLE
  • 61. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Creating the UnpaidOrder Table The following SQL statement creates the UnpaidOrder table in the CoffeeDB database: The REFERENCES qualifier ensures referential integrity between tables The CustomerNumber in the UnpaidOrder table must contain a valid CustomerNumber from the Customer table The ProdNum in the UnpaidOrder table must contain a valid ProdNum from the Coffee table CREATE TABLE UnpaidOrder ( CustomerNumber CHAR(10) NOT NULL REFERENCES Customer(CustomerNumber), ProdNum CHAR(10) NOT NULL REFERENCES Coffee(ProdNum), OrderDate CHAR(10), Quantity DOUBLE, Cost DOUBLE )
  • 62. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Entity Relationship Diagrams An entity relationship diagram shows the relationships between tables Primary keys are denoted with (PK) Lines drawn between tables show how they are related The ends of each line show either a 1 or an infinity symbol (∞) The infinity symbol means many and number 1 means one. A one to many relationship means that for each row in table A there can be many rows in table B that reference it. A many to one relationship means that many rows in table A can reference a single row in table B.
  • 63. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CoffeeDB Relationships Left to Right One to many relationship between Customer and UnpaidOrder One row in the Customer table may be referenced by many rows in the UnpaidOrder table Many to one relationship between the UnpaidOrder and Coffee tables Many rows in the UnpaidOrder table may reference a single row in the Coffee table.
  • 64. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CoffeeDB Relationships Right to Left One to many relationship between Coffee and UnpaidOrder One row in the Coffee table may be referenced by many rows in the UnpaidOrder table Many to one relationship between UnpaidOrder and Customer Many rows in the UnpaidOrder table may reference a single row in the Customer table.
  • 65. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Joining Data from Multiple Tables In SQL, you must use qualified column names in a SELECT statement if the tables have columns with the same name A qualified column name takes the following form: Example: The search criteria tell the DBMS how to link the rows in the tables TableName.ColumnName SELECT Customer.CustomerNumber, Customer.Name, UnpaidOrder.OrderDate, UnpaidOrder.Cost, Coffee.Description FROM Customer, UnpaidOrder, Coffee WHERE UnpaidOrder.CustomerNumber = Customer.CustomerNumber AND UnpaidOrder.ProdNum = Coffee.ProdNum
  • 66. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley An Order Entry System The Place Order application uses a relational database (CoffeeDB) Requires the Coffee, Customer, and UnpaidOrder tables Example: CoffeeDBManager.java, CustomerPanel.java, CoffeePanel.java, QtyDatePanel.java, PlaceOrder.java
  • 67. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Transactions An operation that requires multiple database updates is known as a transaction. For a transaction to be complete All of the steps involved in the transaction must be performed. If any single step within a transaction fails None of the steps in the transaction should be performed. When you write transaction-processing code, there are two concepts you must understand: Commit Rollback The term commit refers to making a permanent change to a database The term rollback refers to undoing changes to a database
  • 68. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley JDBC Auto Commit Mode By default, the JDBC Connection class operates in auto commit mode. In auto commit mode All updates that are made to the database are made permanent as soon as they are executed. When auto commit mode is turned off Changes do not become permanent until a commit command is executed A rollback command can be used to undo changes
  • 69. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley JDBC Transaction Methods To turn auto commit mode off Call the Connection class's setAutoCommit method Pass the argument false To execute a commit command Call the Connection class's commit method To execute a rollback command Call the Connection class's conn.setAutoCommit(false); conn.commit(); conn.rollback();
  • 70. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley JDBC Transaction Example conn.setAutoCommit(false); // Attempt the transaction try { // Update the inventory records. stmt.executeUpdate(updateStatement); // Add the order to the UnpaidOrder table. stmt.executeUpdate(insertStatement); // Commit all these updates. conn.commit(); } catch (SQLException ex) { // Roll back the changes. conn.rollback(); } The commit method is called in the try block The rollback method is called in the catch block
  • 71. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Stored Procedures Many commercial database systems allow you to create SQL statements and store them in the DBMS itself These SQL statements are called stored procedures Can be executed by other applications using the DBMS Ideal for SQL statements that are used often in a variety of applications Usually execute faster than SQL statements that are submitted from applications outside the DBMS Each DBMS has its own syntax for creating a stored procedure in SQL To execute a stored procedure, you must create a CallableStatement object CallableStatement is an interface in the java.sql package To create a CallableStatement object, you call the Connection class's prepareCall statement