32slideJDBCDatabaseProgramming
32slideJDBCDatabaseProgramming
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
1
Objectives
To understand the concept of database and database management
systems (§32.2).
To understand the relational data model: relational data structures,
constraints, and languages (§32.2).
To use SQL to create and drop tables, and to retrieve and modify
data (§32.3).
To learn how to load a driver, connect to a database, execute
statements, and process result sets using JDBC (§32.4).
To use prepared statements to execute precompiled SQL statements
(§32.5).
To use callable statements to execute stored SQL procedures and
functions (§32.6).
To explore database metadata using the DatabaseMetaData and
ResultSetMetaData interfaces (§32.7).
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
2
What is a Database System?
e.g., Access,
MySQL, Oracle, and
MS SQL Server
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
3
Database Application Systems
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
4
Rational Database and Relational
Data Model
Most of today’s database systems are relational database
systems, based on the relational data model. A relational data
model has three key A relational data model has three key
components: structure, integrity and languages.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
5
Relational Structure
A relational database consists of a set of
relations. A relation has two things in one: a
schema and an instance of the schema. The
schema defines the relation and an instance is
the content of the relation at a given time. An
instance of a relation is nothing more than a
table with rows and named columns. For
convenience with no confusion, we refer
instances of relations as just relations or tables.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
6
Course Table
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
7
Student Table
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
8
Enrollment
Table
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
9
Table vs. File
NOTE:
A table or a relation is not same as a file.
Most of the relational database systems
store multiple tables in a file.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
10
Integrity Constraints
An integrity constraint imposes a condition that all
legal instances of the relations must satisfy. In
general, there are three types of constraints: domain
constraint, primary key constraint, and foreign key
constraint. Domain constraints and primary key
constraints are known as intra-relational
constraints, meaning that a constraint involves only
one relation. The foreign key constraint is known
as inter-relational, meaning that a constraint
involves more than one relation.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
11
Domain Constraints
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
12
Primary Key Constraints
Enrollment Table ssn courseId dateRegistered grade
constraint
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
13
Foreign Key Constraints
Enrollment Table ssn courseId dateRegistered grade
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
14
Domain Constraints
Domain constraints specify the permissible values
for an attribute. Domains can be specified using
standard data types such as integers, floating-point
numbers, fixed-length strings, and variant-length
strings. The standard data type specifies a broad
range of values. Additional constraints can be
specified to narrow the ranges. You can also specify
whether an attribute can be null.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
15
Domain Constraints Example
create table Course (
courseId char(5),
subjectId char(4) not null,
courseNumber integer,
title varchar(50) not null,
numOfCredits integer,
constraint greaterThanOne
check (numOfCredits >= 1));
);
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
16
Superkey
Superkey A superkey is an attribute or a set of attributes
Key
that uniquely identify the relation. That is, no
two tuples have the same values on the superkey.
Candidate By definition, a relation consists of a set of
key
distinct tuples. The set of all attributes in the
Primary relation forms a superkey.
key
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
17
Key and Candidate Key
Superkey
A key K is a minimal superkey, meaning that any
Key proper subset of K is not a superkey. It is
possible that a relation has several keys. In this
Candidate
key case, each of the keys is called a candidate key.
Primary
key
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
18
Primary Key
Superkey
The primary key is one of the candidate keys
Key designated by the database designer. The primary
key is often used to identify tuples in a relation.
Candidate
key
create table Course(
Primary subjectCode char(4),
key courseNumber int,
title varchar(50), numOfCredits int
constraint greaterThanOne check (numOfCredits >= 1),
primary key (subjectCode, courseNumber));
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
19
Primary Key
The primary key is one of the candidate keys designated by
the database designer. The primary key is often used to
identify tuples in a relation.
create table Course (
courseId char(5),
subjectId char(4) not null,
courseNumber integer,
title varchar(50) not null,
numOfCredits integer,
primary key (courseId)
);
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
20
Primary Key Constraints
The primary key constraint specifies that the primary key
value of a tuple cannot be null and no two tuples in the
relation can have the same value on the primary key. The
DBMS enforces the primary key constraint. For example, if
you attempt to insert a record with the same primary key as
an existing record in the table, the DBMS would report an
error and reject the operation.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
21
Foreign Key Constraints
In a relational database, data are related. Tuples in a
relation are related and tuples in different relations
are related through their common attributes.
Informally speaking, the common attributes are
foreign keys. The foreign key constraints define the
relationships among relations.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
22
Foreign Key Constraints Formal
Definition
Formally, a set of attributes FK is a foreign key in a
relation R that references relation T if it satisfies the
following two rules:
The attributes in FK have the same domain as
the primary key in T.
A non-null value on FK in R must match a
primary key value in T.
FK
R T
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
23
Foreign Key Example
create table Enrollment (
ssn char(9),
courseId char(5),
dateRegistered date,
grade char(1),
primary key (ssn, courseId),
foreign key (ssn) references Student,
foreign key (courseId) references Course
);
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
24
Foreign Key Discussion
A foreign key is not necessarily the primary key or part
of the primary in the relation. For example, subjectCode
is a foreign key in the Course table that references the
Subject table, but it is not the primary key in Course.
departmentCode is a foreign key in the Subject table
that references Department, but it is not the primary key
in Subject.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
25
Foreign Key Discussion, cont.
The referencing relation and the referenced
relation may be the same table. For example,
supervisorId is a foreign key in Faculty that
references facultyId in Faculty.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
26
Foreign Key Discussion, cont.
The foreign key is not necessary to have the
same name as its referenced primary key as long
as they have the same domain. For example,
headId is a foreign key in Department that
references facultyId in Faculty.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
27
Foreign Key Discussion, cont.
A relation may have more than one foreign key.
For example, headId and collegeCode are both
foreign keys in Department.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
28
SQL
Structured Query Language, pronounced S-Q-L, or Sequel
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
29
Examples of simple SQL statements
Create table create table Course ( create table Student (
courseId char(5), ssn char(9),
Drop table firstName varchar(25),
Describe table subjectId char(4) not null, mi char(1),
Select courseNumber integer, lastName varchar(25),
title varchar(50) not null, birthDate date,
Insert street varchar(25),
numOfCredits integer,
Delete phone char(11),
primary key (courseId)
Update zipCode char(5),
); deptId char(4),
primary key (ssn)
);
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
30
Examples of simple SQL statements
Create table drop table Enrollment;
Drop table drop table Course;
Describe table drop table Student;
Select
Insert
Delete
Update
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
31
Examples of simple SQL statements
Create table describe Course; -- Oracle
Drop table
Describe table
Select
Insert
Delete
Update
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
32
Examples of simple SQL statements
Create table select firstName, mi, lastName
Drop table from Student
Describe table where deptId = 'CS';
Select
select firstName, mi, lastName
Insert
from Student
Delete
where deptId = 'CS' and zipCode = '31411';
Update
select *
from Student
where deptId = 'CS' and zipCode = '31411';
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
33
Examples of simple SQL statements
Create table insert into Course (courseId, subjectId, courseNumber, title)
Drop table values ('11113', 'CSCI', '3720', 'Database Systems', 3);
Describe table
Select
Insert
Delete
Update
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
34
Examples of simple SQL statements
Create table update Course
Drop table set numOfCredits = 4
Describe table where title = 'Database Systems';
Select
Insert
Update
Delete
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
35
Examples of simple SQL statements
Create table delete Course
Drop table where title = 'Database System';
Describe table
Select
Insert
Update
Delete
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
36
Why Java for Database Programming?
First, Java is platform independent. You can develop
platform-independent database applications using SQL
and Java for any relational database systems.
Second, the support for accessing database systems from
Java is built into Java API, so you can create database
applications using all Java code with a common
interface.
Third, Java is taught in almost every university either as
the first programming language or as the second
programming language.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
37
Database Applications Using Java
GUI
Client/Server
Server-Side programming
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
38
The Architecture of JDBC
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
39
The JDBC Interfaces
Loading
drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
40
Developing JDBC Programs
Loading Statement to load a driver:
drivers Class.forName("JDBCDriverClass");
To use the MySQL and Oracle drivers, you have to add mysqljdbc.jar and
classes12.jar in the classpath using the following DOS command on
Windows:
classpath=%classpath%;c:\book\mysqljdbc.jar;c:\book\classes12.jar
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
41
Developing JDBC Programs
Loading Connection connection = DriverManager.getConnection(databaseURL);
drivers
Database URL Pattern
Establishing Access jdbc:odbc:dataSource
connections MySQL jdbc:mysql://hostname/dbname
Creating and Oracle jdbc:oracle:thin:@hostname:port#:oracleDBSID
executing
Examples: See Supplement IV.D for
statements
creating an ODBC data source
For Access:
Processing Connection connection = DriverManager.getConnection
ResultSet ("jdbc:odbc:ExampleMDBDataSource");
For MySQL:
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/test");
For Oracle:
Connection connection = DriverManager.getConnection
("jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl", "scott", "tiger");
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
42
Developing JDBC Programs
Loading Creating statement:
drivers Statement statement = connection.createStatement();
Establishing
connections Executing statement (for update, delete, insert):
statement.executeUpdate
Creating and ("create table Temp (col1 char(5), col2 char(5))");
executing
statements Executing statement (for select):
// Select the columns from the Student table
Processing
ResultSet resultSet = statement.executeQuery
ResultSet
("select firstName, mi, lastName from Student where lastName "
+ " = 'Smith'");
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
43
Developing JDBC Programs
Loading Executing statement (for select):
drivers // Select the columns from the Student table
ResultSet resultSet = stmt.executeQuery
Establishing
("select firstName, mi, lastName from Student where lastName "
connections
+ " = 'Smith'");
Creating and
executing Processing ResultSet (for select):
statements // Iterate through the result and print the student names
while (resultSet.next())
Processing System.out.println(resultSet.getString(1) + " " + resultSet.getString(2)
ResultSet + ". " + resultSet.getString(3));
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
44
import java.sql.*;
public class SimpleJdbc {
public static void main(String[] args) Simple
throws SQLException, ClassNotFoundException {
// Load the JDBC driver JDBC
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded"); Example
// Establish a connection
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/test");
System.out.println("Database connected");
// Create a statement
Statement statement = connection.createStatement();
// Execute a statement
ResultSet resultSet = statement.executeQuery
("select firstName, mi, lastName from Student where lastName "
+ " = 'Smith'");
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
46
Example:
Accessing Database from JavaFX
This example demonstrates connecting to a
database from a Java applet. The applet lets the
user enter the SSN and the course ID to find a
student’s grade.
FindGrade Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
47
Processing Statements
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
48
Processing Statements Diagram
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
49
The execute, executeQuery, and
executeUpdate Methods
The methods for executing SQL statements are
execute, executeQuery, and executeUpdate, each
of which accepts a string containing a SQL
statement as an argument. This string is passed to
the database for execution. The execute method
should be used if the execution produces multiple
result sets, multiple update counts, or a
combination of result sets and update counts.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
50
The execute, executeQuery, and
executeUpdate Methods, cont.
The executeQuery method should be used if
the execution produces a single result set,
such as the SQL select statement. The
executeUpdate method should be used if the
statement results in a single update count or
no update count, such as a SQL INSERT,
DELETE, UPDATE, or DDL statement.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
51
PreparedStatement
The PreparedStatement interface is designed
to execute dynamic SQL statements and
SQL-stored procedures with IN parameters.
These SQL statements and stored procedures
are precompiled for efficient use when
repeatedly executed.
Statement pstmt = connection.prepareStatement
("insert into Student (firstName, mi, lastName) +
values (?, ?, ?)");
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
52
Example:
Using PreparedStatement to Execute
Dynamic SQL Statements
This example rewrites the preceding example
using PreparedStatement.
FindGradeUsingPreparedStatement Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
53
Retrieving Database Metadata
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
54
DatabaseMetadata, cont.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
55
General Information
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
56
Obtaining Database Capabilities
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
57
Obtaining Object Descriptions
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
58
DatabaseMetaData dbMetaData = connection.getMetaData();
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
60