SlideShare a Scribd company logo
1 of 60
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
1
Chapter 34 Java Database Programming
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
2
Objectives
To understand the concept of database and database management
systems (§34.2).
To understand the relational data model: relational data structures,
constraints, and languages (§34.2).
To use SQL to create and drop tables, and to retrieve and modify
data (§34.3).
To learn how to load a driver, connect to a database, execute
statements, and process result sets using JDBC (§34.4).
To use prepared statements to execute precompiled SQL statements
(§34.5).
To use callable statements to execute stored SQL procedures and
functions (§34.6).
To explore database metadata using the DatabaseMetaData and
ResultSetMetaData interfaces (§34.7).
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
3
What is a Database System?
Database Management System (DBMS)
Application Programs
System Users
Application Users
database
e.g., Access,
MySQL, Oracle, and
MS SQL Server
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
4
Database Application Systems
Database Management System
… database
Application Programs
Application Users
Database Management System
…
…
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
5
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 components: structure, integrity and
languages.
 Structure defines the representation of the data.
 Integrity imposes constraints on the data.
 Language provides the means for accessing and
manipulating data.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
6
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.
7
Course Table
Course Table
courseId subjectId courseNumber title numOfCredits
11111 CSCI 1301 Introduction to Java I 4
11112 CSCI 1302 Introduction to Java II 3
11113 CSCI 3720 Database Systems 3
11114 CSCI 4750 Rapid Java Application 3
11115 MATH 2750 Calculus I 5
11116 MATH 3750 Calculus II 5
11117 EDUC 1111 Reading 3
11118 ITEC 1344 Database Administration 3
Columns/Attributes
Tuples/
Rows
Relation/Table Name
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
8
Student Table
Student Table
ssn firstName mi lastName phone birthDate street zipCode deptID
444111110 Jacob R Smith 9129219434 1985-04-09 99 Kingston Street 31435 BIOL
444111111 John K Stevenson 9129219434 null 100 Main Street 31411 BIOL
444111112 George K Smith 9129213454 1974-10-10 1200 Abercorn St. 31419 CS
444111113 Frank E Jones 9125919434 1970-09-09 100 Main Street 31411 BIOL
444111114 Jean K Smith 9129219434 1970-02-09 100 Main Street 31411 CHEM
444111115 Josh R Woo 7075989434 1970-02-09 555 Franklin St. 31411 CHEM
444111116 Josh R Smith 9129219434 1973-02-09 100 Main Street 31411 BIOL
444111117 Joy P Kennedy 9129229434 1974-03-19 103 Bay Street 31412 CS
444111118 Toni R Peterson 9129229434 1964-04-29 103 Bay Street 31412 MATH
444111119 Patrick R Stoneman 9129229434 1969-04-29 101 Washington St. 31435 MATH
444111120 Rick R Carter 9125919434 1986-04-09 19 West Ford St. 31411 BIOL
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
9
Enrollment
Table
Enrollment Table
ssn courseId dateRegistered grade
444111110 11111 2004-03-19 A
444111110 11112 2004-03-19 B
444111110 11113 2004-03-19 C
444111111 11111 2004-03-19 D
444111111 11112 2004-03-19 F
444111111 11113 2004-03-19 A
444111112 11114 2004-03-19 B
444111112 11115 2004-03-19 C
444111112 11116 2004-03-19 D
444111113 11111 2004-03-19 A
444111113 11113 2004-03-19 A
444111114 11115 2004-03-19 B
444111115 11115 2004-03-19 F
444111115 11116 2004-03-19 F
444111116 11111 2004-03-19 D
444111117 11111 2004-03-19 D
444111118 11111 2004-03-19 A
444111118 11112 2004-03-19 D
444111118 11113 2004-03-19 B
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
10
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.
11
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.
12
Domain Constraints
courseId subjectId courseNumber title numOfCredits
11111 CSCI 1301 Introduction to Java I 4
11112 CSCI 1302 Introduction to Java II 3
11113 CSCI 3720 Database Systems 3
...
ssn courseId dateRegistered grade
444111110 11111 2004-03-19 A
444111110 11112 2004-03-19 B
444111110 11113 2004-03-19 C
...
Course Table
Each value in the
numOfCredits column must be
greater than 0 and less than 5
Each value in courseId in the
Enrollment table must match a value
in courseId in the Course table
Each row must have a
value for couserId, and
the value must be unique
Enrollment Table
domain
constra
int
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
13
Primary Key Constraints
courseId subjectId courseNumber title numOfCredits
11111 CSCI 1301 Introduction to Java I 4
11112 CSCI 1302 Introduction to Java II 3
11113 CSCI 3720 Database Systems 3
...
ssn courseId dateRegistered grade
444111110 11111 2004-03-19 A
444111110 11112 2004-03-19 B
444111110 11113 2004-03-19 C
...
Course Table
Each value in the
numOfCredits column must be
greater than 0 and less than 5
Each value in courseId in the
Enrollment table must match a value
in courseId in the Course table
Each row must have a
value for couserId, and
the value must be unique
Enrollment Table
Primary key
constraint
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
14
Foreign Key Constraints
courseId subjectId courseNumber title numOfCredits
11111 CSCI 1301 Introduction to Java I 4
11112 CSCI 1302 Introduction to Java II 3
11113 CSCI 3720 Database Systems 3
...
ssn courseId dateRegistered grade
444111110 11111 2004-03-19 A
444111110 11112 2004-03-19 B
444111110 11113 2004-03-19 C
...
Course Table
Each value in the
numOfCredits column must be
greater than 0 and less than 5
Each value in courseId in the
Enrollment table must match a value
in courseId in the Course table
Each row must have a
value for couserId, and
the value must be unique
Enrollment Table
Foreign key
constraint
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
15
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.
16
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.
17
Superkey
Superkey
Key
Candidate
key
Primary
key
A superkey is an attribute or a set of attributes
that uniquely identify the relation. That is, no
two tuples have the same values on the superkey.
By definition, a relation consists of a set of
distinct tuples. The set of all attributes in the
relation forms a superkey.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
18
Key and Candidate Key
Superkey
Key
Candidate
key
Primary
key
A key K is a minimal superkey, meaning that any
proper subset of K is not a superkey. It is
possible that a relation has several keys. In this
case, each of the keys is called a candidate key.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
19
Primary Key
Superkey
Key
Candidate
key
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(
subjectCode char(4),
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.
20
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.
21
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.
22
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.
23
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.
R T
FK
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
24
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.
25
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.
26
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.
27
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.
28
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.
29
SQL
Structured Query Language, pronounced S-Q-L, or Sequel
To access or write applications for database systems, you need
to use the Structured Query Language (SQL). SQL is the
universal language for accessing relational database
systems. Application programs may allow users to access
database without directly using SQL, but these applications
themselves must use SQL to access the database.
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
Describe table
Select
Insert
Delete
Update
create table Course (
courseId char(5),
subjectId char(4) not null,
courseNumber integer,
title varchar(50) not null,
numOfCredits integer,
primary key (courseId)
);
create table Student (
ssn char(9),
firstName varchar(25),
mi char(1),
lastName varchar(25),
birthDate date,
street varchar(25),
phone char(11),
zipCode char(5),
deptId char(4),
primary key (ssn)
);
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
31
Examples of simple SQL statements
Create table
Drop table
Describe table
Select
Insert
Delete
Update
drop table Enrollment;
drop table Course;
drop table Student;
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
32
Examples of simple SQL statements
Create table
Drop table
Describe table
Select
Insert
Delete
Update
describe Course; -- Oracle
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
33
Examples of simple SQL statements
Create table
Drop table
Describe table
Select
Insert
Delete
Update
select firstName, mi, lastName
from Student
where deptId = 'CS';
select firstName, mi, lastName
from Student
where deptId = 'CS' and zipCode = '31411';
select *
from Student
where deptId = 'CS' and zipCode = '31411';
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
34
Examples of simple SQL statements
Create table
Drop table
Describe table
Select
Insert
Delete
Update
insert into Course (courseId, subjectId, courseNumber, title)
values ('11113', 'CSCI', '3720', 'Database Systems', 3);
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
35
Examples of simple SQL statements
Create table
Drop table
Describe table
Select
Insert
Update
Delete
update Course
set numOfCredits = 4
where title = 'Database Systems';
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
36
Examples of simple SQL statements
Create table
Drop table
Describe table
Select
Insert
Update
Delete
delete Course
where title = 'Database System';
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
37
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.
38
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.
39
The Architecture of JDBC
Java Applications/
Applets
JDBC API
Oracle JDBC
Driver
JDBC-ODBC
Bridge Driver
Local or remote
ORACLE DB
Oracle ODBC
Driver
Microsoft
ODBC Driver
Microsoft Access
Database
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
40
The JDBC Interfaces
Driver
Connection Connection
Statement Statement Statement Statement
ResultSet ResultSet ResultSet ResultSet
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.
41
Developing JDBC Programs
Loading
drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
Statement to load a driver:
Class.forName("JDBCDriverClass");
A driver is a class. For example:
Database Driver Class Source
Access sun.jdbc.odbc.JdbcOdbcDriver Already in JDK
MySQL com.mysql.jdbc.Driver Website
Oracle oracle.jdbc.driver.OracleDriver Website
The JDBC-ODBC driver for Access is bundled in JDK.
MySQL driver class is in mysqljdbc.jar
Oracle driver class is in classes12.jar
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:bookmysqljdbc.jar;c:bookclasses12.jar
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
42
Developing JDBC Programs
Loading
drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
Connection connection = DriverManager.getConnection(databaseURL);
Database URL Pattern
Access jdbc:odbc:dataSource
MySQL jdbc:mysql://hostname/dbname
Oracle jdbc:oracle:thin:@hostname:port#:oracleDBSID
Examples:
For Access:
Connection connection = DriverManager.getConnection
("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");
See Supplement IV.D for
creating an ODBC data source
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
43
Developing JDBC Programs
Loading
drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
Creating statement:
Statement statement = connection.createStatement();
Executing statement (for update, delete, insert):
statement.executeUpdate
("create table Temp (col1 char(5), col2 char(5))");
Executing statement (for select):
// Select the columns from the Student table
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.
44
Developing JDBC Programs
Loading
drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
Executing statement (for select):
// Select the columns from the Student table
ResultSet resultSet = stmt.executeQuery
("select firstName, mi, lastName from Student where lastName "
+ " = 'Smith'");
Processing ResultSet (for select):
// Iterate through the result and print the student names
while (resultSet.next())
System.out.println(resultSet.getString(1) + " " + resultSet.getString(2)
+ ". " + resultSet.getString(3));
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
45
import java.sql.*;
public class SimpleJdbc {
public static void main(String[] args)
throws SQLException, ClassNotFoundException {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded");
// 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'");
// Iterate through the result and print the student names
while (resultSet.next())
System.out.println(resultSet.getString(1) + "t" +
resultSet.getString(2) + "t" + resultSet.getString(3));
// Close the connection
connection.close();
}
}
Simple
JDBC
Example
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
46
Creating ODBC Data Source
Please follow the steps in Supplement on the Companion
Website to create an ODBC data source on Windows.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
47
Example:
Accessing Database from Java Applets
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
NOTE: To run this program from here, you need:
1. To have a MySQL database setup just like the one in the text.
2. Set MySQL JDBC driver in the classpath.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
48
Processing Statements
Once a connection to a particular database is
established, it can be used to send SQL statements
from your program to the database. JDBC provides
the Statement, PreparedStatement, and
CallableStatement interfaces to facilitate sending
statements to a database for execution and
receiving execution results from the database.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
49
Processing Statements Diagram
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
50
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.
51
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.
52
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.
53
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.
54
Retrieving Database Metadata
Database metadata is the information that
describes database itself. JDBC provides the
DatabaseMetaData interface for obtaining
database wide information and the
ResultSetMetaData interface for obtaining the
information on the specific ResultSet.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
55
DatabaseMetadata, cont.
The DatabaseMetaData interface provides
more than 100 methods for getting database
metadata concerning the database as a whole.
These methods can be divided into three
groups: for retrieving general information, for
finding database capabilities, and for getting
object descriptions.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
56
General Information
The general information includes the URL,
username, product name, product version,
driver name, driver version, available
functions, available data types and so on.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
57
Obtaining Database Capabilities
The examples of the database capabilities are
whether the database supports the GROUP BY
operator, the ALTER TABLE command with
add column option, supports entry-level or full
ANSI92 SQL grammar.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
58
Obtaining Object Descriptions
the examples of the database objects are
tables, views, and procedures.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
59
DatabaseMetaData dbMetaData = connection.getMetaData();
System.out.println("database URL: " +
dbMetaData.getURL());
System.out.println("database username: " +
dbMetaData.getUserName());
System.out.println("database product name: " +
dbMetaData.getDatabaseProductName());
System.out.println("database product version: " +
dbMetaData.getDatabaseProductVersion());
System.out.println("JDBC driver name: " +
dbMetaData.getDriverName());
System.out.println("JDBC driver version: " +
dbMetaData.getDriverVersion());
System.out.println("JDBC driver major version: " +
new Integer(dbMetaData.getDriverMajorVersion()));
System.out.println("JDBC driver minor version: " +
new Integer(dbMetaData.getDriverMinorVersion()));
System.out.println("Max number of connections: " +
new Integer(dbMetaData.getMaxConnections()));
System.out.println("MaxTableNameLentgh: " +
new Integer(dbMetaData.getMaxTableNameLength()));
System.out.println("MaxColumnsInTable: " +
new Integer(dbMetaData.getMaxColumnsInTable()));
connection.close();
Examples
Sample run on
next slide
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
60
Sample Run

More Related Content

Similar to 34slideDatabaseProgramming.ppt

L1 Intro to Relational DBMS LP.pdfIntro to Relational .docx
L1 Intro to Relational DBMS LP.pdfIntro to Relational .docxL1 Intro to Relational DBMS LP.pdfIntro to Relational .docx
L1 Intro to Relational DBMS LP.pdfIntro to Relational .docxDIPESH30
 
IT6701-Information Management Unit 1
IT6701-Information Management Unit 1IT6701-Information Management Unit 1
IT6701-Information Management Unit 1SIMONTHOMAS S
 
Data-Structure-original-QuantumSupply.pdf
Data-Structure-original-QuantumSupply.pdfData-Structure-original-QuantumSupply.pdf
Data-Structure-original-QuantumSupply.pdflehal93146
 
09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects conceptkavitamittal18
 
Sample Question Paper IP Class xii
Sample Question Paper IP Class xii Sample Question Paper IP Class xii
Sample Question Paper IP Class xii kvs
 
Java™ (OOP) - Chapter 8: "Objects and Classes"
Java™ (OOP) - Chapter 8: "Objects and Classes"Java™ (OOP) - Chapter 8: "Objects and Classes"
Java™ (OOP) - Chapter 8: "Objects and Classes"Gouda Mando
 
41slideAdvancedDatabaseProgramming.ppt
41slideAdvancedDatabaseProgramming.ppt41slideAdvancedDatabaseProgramming.ppt
41slideAdvancedDatabaseProgramming.pptMohammedNouh7
 
PROGRAMMING COURSE DATA STRUCTURES
PROGRAMMING COURSE DATA STRUCTURESPROGRAMMING COURSE DATA STRUCTURES
PROGRAMMING COURSE DATA STRUCTURESBALUJAINSTITUTE
 
dbms final.pdf
dbms final.pdfdbms final.pdf
dbms final.pdfRaKesh3868
 
lab14444444444444444444444444444444444444444
lab14444444444444444444444444444444444444444lab14444444444444444444444444444444444444444
lab14444444444444444444444444444444444444444227567
 
files_1570175665_204715750.pdf
files_1570175665_204715750.pdffiles_1570175665_204715750.pdf
files_1570175665_204715750.pdfbeherapravat936
 
LiangChapter4 Unicode , ASCII Code .ppt
LiangChapter4 Unicode , ASCII Code  .pptLiangChapter4 Unicode , ASCII Code  .ppt
LiangChapter4 Unicode , ASCII Code .pptzainiiqbal761
 
UNIT 2 Structured query language commands
UNIT 2 Structured query language commandsUNIT 2 Structured query language commands
UNIT 2 Structured query language commandsBhakti Pawar
 

Similar to 34slideDatabaseProgramming.ppt (20)

L1 Intro to Relational DBMS LP.pdfIntro to Relational .docx
L1 Intro to Relational DBMS LP.pdfIntro to Relational .docxL1 Intro to Relational DBMS LP.pdfIntro to Relational .docx
L1 Intro to Relational DBMS LP.pdfIntro to Relational .docx
 
slides 01.ppt
slides 01.pptslides 01.ppt
slides 01.ppt
 
10slide.ppt
10slide.ppt10slide.ppt
10slide.ppt
 
IT6701-Information Management Unit 1
IT6701-Information Management Unit 1IT6701-Information Management Unit 1
IT6701-Information Management Unit 1
 
Data-Structure-original-QuantumSupply.pdf
Data-Structure-original-QuantumSupply.pdfData-Structure-original-QuantumSupply.pdf
Data-Structure-original-QuantumSupply.pdf
 
09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept
 
09slide.ppt
09slide.ppt09slide.ppt
09slide.ppt
 
Sample Question Paper IP Class xii
Sample Question Paper IP Class xii Sample Question Paper IP Class xii
Sample Question Paper IP Class xii
 
Java™ (OOP) - Chapter 8: "Objects and Classes"
Java™ (OOP) - Chapter 8: "Objects and Classes"Java™ (OOP) - Chapter 8: "Objects and Classes"
Java™ (OOP) - Chapter 8: "Objects and Classes"
 
Bc0041
Bc0041Bc0041
Bc0041
 
41slideAdvancedDatabaseProgramming.ppt
41slideAdvancedDatabaseProgramming.ppt41slideAdvancedDatabaseProgramming.ppt
41slideAdvancedDatabaseProgramming.ppt
 
PROGRAMMING COURSE DATA STRUCTURES
PROGRAMMING COURSE DATA STRUCTURESPROGRAMMING COURSE DATA STRUCTURES
PROGRAMMING COURSE DATA STRUCTURES
 
dbms final.pdf
dbms final.pdfdbms final.pdf
dbms final.pdf
 
Oop r&s may 2019
Oop r&s may 2019Oop r&s may 2019
Oop r&s may 2019
 
Core java online training
Core java online trainingCore java online training
Core java online training
 
Lesson 2.2 abstraction
Lesson 2.2   abstractionLesson 2.2   abstraction
Lesson 2.2 abstraction
 
lab14444444444444444444444444444444444444444
lab14444444444444444444444444444444444444444lab14444444444444444444444444444444444444444
lab14444444444444444444444444444444444444444
 
files_1570175665_204715750.pdf
files_1570175665_204715750.pdffiles_1570175665_204715750.pdf
files_1570175665_204715750.pdf
 
LiangChapter4 Unicode , ASCII Code .ppt
LiangChapter4 Unicode , ASCII Code  .pptLiangChapter4 Unicode , ASCII Code  .ppt
LiangChapter4 Unicode , ASCII Code .ppt
 
UNIT 2 Structured query language commands
UNIT 2 Structured query language commandsUNIT 2 Structured query language commands
UNIT 2 Structured query language commands
 

More from MohammedNouh7

JavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptJavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptMohammedNouh7
 
Chapter7 database management system.pptx
Chapter7 database management system.pptxChapter7 database management system.pptx
Chapter7 database management system.pptxMohammedNouh7
 
Introduction to database m Chapter 9.pptx
Introduction to database m Chapter 9.pptxIntroduction to database m Chapter 9.pptx
Introduction to database m Chapter 9.pptxMohammedNouh7
 
database management system lessonchapter
database management system lessonchapterdatabase management system lessonchapter
database management system lessonchapterMohammedNouh7
 

More from MohammedNouh7 (9)

JavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptJavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.ppt
 
Chapter7 database management system.pptx
Chapter7 database management system.pptxChapter7 database management system.pptx
Chapter7 database management system.pptx
 
Introduction to database m Chapter 9.pptx
Introduction to database m Chapter 9.pptxIntroduction to database m Chapter 9.pptx
Introduction to database m Chapter 9.pptx
 
database management system lessonchapter
database management system lessonchapterdatabase management system lessonchapter
database management system lessonchapter
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
 
Ch13.pptx
Ch13.pptxCh13.pptx
Ch13.pptx
 
Ch21.pptx
Ch21.pptxCh21.pptx
Ch21.pptx
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityVictorSzoltysek
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceIES VE
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governanceWSO2
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....rightmanforbloodline
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseWSO2
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 

Recently uploaded (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 

34slideDatabaseProgramming.ppt

  • 1. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 34 Java Database Programming
  • 2. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 2 Objectives To understand the concept of database and database management systems (§34.2). To understand the relational data model: relational data structures, constraints, and languages (§34.2). To use SQL to create and drop tables, and to retrieve and modify data (§34.3). To learn how to load a driver, connect to a database, execute statements, and process result sets using JDBC (§34.4). To use prepared statements to execute precompiled SQL statements (§34.5). To use callable statements to execute stored SQL procedures and functions (§34.6). To explore database metadata using the DatabaseMetaData and ResultSetMetaData interfaces (§34.7).
  • 3. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 3 What is a Database System? Database Management System (DBMS) Application Programs System Users Application Users database e.g., Access, MySQL, Oracle, and MS SQL Server
  • 4. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4 Database Application Systems Database Management System … database Application Programs Application Users Database Management System … …
  • 5. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 5 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 components: structure, integrity and languages.  Structure defines the representation of the data.  Integrity imposes constraints on the data.  Language provides the means for accessing and manipulating data.
  • 6. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6 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.
  • 7. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 7 Course Table Course Table courseId subjectId courseNumber title numOfCredits 11111 CSCI 1301 Introduction to Java I 4 11112 CSCI 1302 Introduction to Java II 3 11113 CSCI 3720 Database Systems 3 11114 CSCI 4750 Rapid Java Application 3 11115 MATH 2750 Calculus I 5 11116 MATH 3750 Calculus II 5 11117 EDUC 1111 Reading 3 11118 ITEC 1344 Database Administration 3 Columns/Attributes Tuples/ Rows Relation/Table Name
  • 8. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 8 Student Table Student Table ssn firstName mi lastName phone birthDate street zipCode deptID 444111110 Jacob R Smith 9129219434 1985-04-09 99 Kingston Street 31435 BIOL 444111111 John K Stevenson 9129219434 null 100 Main Street 31411 BIOL 444111112 George K Smith 9129213454 1974-10-10 1200 Abercorn St. 31419 CS 444111113 Frank E Jones 9125919434 1970-09-09 100 Main Street 31411 BIOL 444111114 Jean K Smith 9129219434 1970-02-09 100 Main Street 31411 CHEM 444111115 Josh R Woo 7075989434 1970-02-09 555 Franklin St. 31411 CHEM 444111116 Josh R Smith 9129219434 1973-02-09 100 Main Street 31411 BIOL 444111117 Joy P Kennedy 9129229434 1974-03-19 103 Bay Street 31412 CS 444111118 Toni R Peterson 9129229434 1964-04-29 103 Bay Street 31412 MATH 444111119 Patrick R Stoneman 9129229434 1969-04-29 101 Washington St. 31435 MATH 444111120 Rick R Carter 9125919434 1986-04-09 19 West Ford St. 31411 BIOL
  • 9. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 9 Enrollment Table Enrollment Table ssn courseId dateRegistered grade 444111110 11111 2004-03-19 A 444111110 11112 2004-03-19 B 444111110 11113 2004-03-19 C 444111111 11111 2004-03-19 D 444111111 11112 2004-03-19 F 444111111 11113 2004-03-19 A 444111112 11114 2004-03-19 B 444111112 11115 2004-03-19 C 444111112 11116 2004-03-19 D 444111113 11111 2004-03-19 A 444111113 11113 2004-03-19 A 444111114 11115 2004-03-19 B 444111115 11115 2004-03-19 F 444111115 11116 2004-03-19 F 444111116 11111 2004-03-19 D 444111117 11111 2004-03-19 D 444111118 11111 2004-03-19 A 444111118 11112 2004-03-19 D 444111118 11113 2004-03-19 B
  • 10. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 10 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.
  • 11. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 11 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.
  • 12. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 12 Domain Constraints courseId subjectId courseNumber title numOfCredits 11111 CSCI 1301 Introduction to Java I 4 11112 CSCI 1302 Introduction to Java II 3 11113 CSCI 3720 Database Systems 3 ... ssn courseId dateRegistered grade 444111110 11111 2004-03-19 A 444111110 11112 2004-03-19 B 444111110 11113 2004-03-19 C ... Course Table Each value in the numOfCredits column must be greater than 0 and less than 5 Each value in courseId in the Enrollment table must match a value in courseId in the Course table Each row must have a value for couserId, and the value must be unique Enrollment Table domain constra int
  • 13. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 13 Primary Key Constraints courseId subjectId courseNumber title numOfCredits 11111 CSCI 1301 Introduction to Java I 4 11112 CSCI 1302 Introduction to Java II 3 11113 CSCI 3720 Database Systems 3 ... ssn courseId dateRegistered grade 444111110 11111 2004-03-19 A 444111110 11112 2004-03-19 B 444111110 11113 2004-03-19 C ... Course Table Each value in the numOfCredits column must be greater than 0 and less than 5 Each value in courseId in the Enrollment table must match a value in courseId in the Course table Each row must have a value for couserId, and the value must be unique Enrollment Table Primary key constraint
  • 14. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 14 Foreign Key Constraints courseId subjectId courseNumber title numOfCredits 11111 CSCI 1301 Introduction to Java I 4 11112 CSCI 1302 Introduction to Java II 3 11113 CSCI 3720 Database Systems 3 ... ssn courseId dateRegistered grade 444111110 11111 2004-03-19 A 444111110 11112 2004-03-19 B 444111110 11113 2004-03-19 C ... Course Table Each value in the numOfCredits column must be greater than 0 and less than 5 Each value in courseId in the Enrollment table must match a value in courseId in the Course table Each row must have a value for couserId, and the value must be unique Enrollment Table Foreign key constraint
  • 15. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 15 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.
  • 16. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 16 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));
  • 17. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 17 Superkey Superkey Key Candidate key Primary key A superkey is an attribute or a set of attributes that uniquely identify the relation. That is, no two tuples have the same values on the superkey. By definition, a relation consists of a set of distinct tuples. The set of all attributes in the relation forms a superkey.
  • 18. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 18 Key and Candidate Key Superkey Key Candidate key Primary key A key K is a minimal superkey, meaning that any proper subset of K is not a superkey. It is possible that a relation has several keys. In this case, each of the keys is called a candidate key.
  • 19. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 19 Primary Key Superkey Key Candidate key 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( subjectCode char(4), courseNumber int, title varchar(50), numOfCredits int constraint greaterThanOne check (numOfCredits >= 1), primary key (subjectCode, courseNumber));
  • 20. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 20 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) );
  • 21. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 21 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.
  • 22. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 22 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.
  • 23. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 23 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. R T FK
  • 24. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 24 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 );
  • 25. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 25 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.
  • 26. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 26 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.
  • 27. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 27 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.
  • 28. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 28 Foreign Key Discussion, cont. A relation may have more than one foreign key. For example, headId and collegeCode are both foreign keys in Department.
  • 29. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 29 SQL Structured Query Language, pronounced S-Q-L, or Sequel To access or write applications for database systems, you need to use the Structured Query Language (SQL). SQL is the universal language for accessing relational database systems. Application programs may allow users to access database without directly using SQL, but these applications themselves must use SQL to access the database.
  • 30. 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 Describe table Select Insert Delete Update create table Course ( courseId char(5), subjectId char(4) not null, courseNumber integer, title varchar(50) not null, numOfCredits integer, primary key (courseId) ); create table Student ( ssn char(9), firstName varchar(25), mi char(1), lastName varchar(25), birthDate date, street varchar(25), phone char(11), zipCode char(5), deptId char(4), primary key (ssn) );
  • 31. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 31 Examples of simple SQL statements Create table Drop table Describe table Select Insert Delete Update drop table Enrollment; drop table Course; drop table Student;
  • 32. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 32 Examples of simple SQL statements Create table Drop table Describe table Select Insert Delete Update describe Course; -- Oracle
  • 33. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 33 Examples of simple SQL statements Create table Drop table Describe table Select Insert Delete Update select firstName, mi, lastName from Student where deptId = 'CS'; select firstName, mi, lastName from Student where deptId = 'CS' and zipCode = '31411'; select * from Student where deptId = 'CS' and zipCode = '31411';
  • 34. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 34 Examples of simple SQL statements Create table Drop table Describe table Select Insert Delete Update insert into Course (courseId, subjectId, courseNumber, title) values ('11113', 'CSCI', '3720', 'Database Systems', 3);
  • 35. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 35 Examples of simple SQL statements Create table Drop table Describe table Select Insert Update Delete update Course set numOfCredits = 4 where title = 'Database Systems';
  • 36. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 36 Examples of simple SQL statements Create table Drop table Describe table Select Insert Update Delete delete Course where title = 'Database System';
  • 37. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 37 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.
  • 38. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 38 Database Applications Using Java GUI Client/Server Server-Side programming
  • 39. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 39 The Architecture of JDBC Java Applications/ Applets JDBC API Oracle JDBC Driver JDBC-ODBC Bridge Driver Local or remote ORACLE DB Oracle ODBC Driver Microsoft ODBC Driver Microsoft Access Database
  • 40. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 40 The JDBC Interfaces Driver Connection Connection Statement Statement Statement Statement ResultSet ResultSet ResultSet ResultSet Loading drivers Establishing connections Creating and executing statements Processing ResultSet
  • 41. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 41 Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet Statement to load a driver: Class.forName("JDBCDriverClass"); A driver is a class. For example: Database Driver Class Source Access sun.jdbc.odbc.JdbcOdbcDriver Already in JDK MySQL com.mysql.jdbc.Driver Website Oracle oracle.jdbc.driver.OracleDriver Website The JDBC-ODBC driver for Access is bundled in JDK. MySQL driver class is in mysqljdbc.jar Oracle driver class is in classes12.jar 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:bookmysqljdbc.jar;c:bookclasses12.jar
  • 42. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 42 Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet Connection connection = DriverManager.getConnection(databaseURL); Database URL Pattern Access jdbc:odbc:dataSource MySQL jdbc:mysql://hostname/dbname Oracle jdbc:oracle:thin:@hostname:port#:oracleDBSID Examples: For Access: Connection connection = DriverManager.getConnection ("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"); See Supplement IV.D for creating an ODBC data source
  • 43. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 43 Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet Creating statement: Statement statement = connection.createStatement(); Executing statement (for update, delete, insert): statement.executeUpdate ("create table Temp (col1 char(5), col2 char(5))"); Executing statement (for select): // Select the columns from the Student table ResultSet resultSet = statement.executeQuery ("select firstName, mi, lastName from Student where lastName " + " = 'Smith'");
  • 44. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 44 Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet Executing statement (for select): // Select the columns from the Student table ResultSet resultSet = stmt.executeQuery ("select firstName, mi, lastName from Student where lastName " + " = 'Smith'"); Processing ResultSet (for select): // Iterate through the result and print the student names while (resultSet.next()) System.out.println(resultSet.getString(1) + " " + resultSet.getString(2) + ". " + resultSet.getString(3));
  • 45. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 45 import java.sql.*; public class SimpleJdbc { public static void main(String[] args) throws SQLException, ClassNotFoundException { // Load the JDBC driver Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver loaded"); // 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'"); // Iterate through the result and print the student names while (resultSet.next()) System.out.println(resultSet.getString(1) + "t" + resultSet.getString(2) + "t" + resultSet.getString(3)); // Close the connection connection.close(); } } Simple JDBC Example
  • 46. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 46 Creating ODBC Data Source Please follow the steps in Supplement on the Companion Website to create an ODBC data source on Windows.
  • 47. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 47 Example: Accessing Database from Java Applets 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 NOTE: To run this program from here, you need: 1. To have a MySQL database setup just like the one in the text. 2. Set MySQL JDBC driver in the classpath.
  • 48. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 48 Processing Statements Once a connection to a particular database is established, it can be used to send SQL statements from your program to the database. JDBC provides the Statement, PreparedStatement, and CallableStatement interfaces to facilitate sending statements to a database for execution and receiving execution results from the database.
  • 49. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 49 Processing Statements Diagram
  • 50. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 50 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.
  • 51. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 51 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.
  • 52. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 52 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 (?, ?, ?)");
  • 53. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 53 Example: Using PreparedStatement to Execute Dynamic SQL Statements This example rewrites the preceding example using PreparedStatement. FindGradeUsingPreparedStatement Run
  • 54. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 54 Retrieving Database Metadata Database metadata is the information that describes database itself. JDBC provides the DatabaseMetaData interface for obtaining database wide information and the ResultSetMetaData interface for obtaining the information on the specific ResultSet.
  • 55. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 55 DatabaseMetadata, cont. The DatabaseMetaData interface provides more than 100 methods for getting database metadata concerning the database as a whole. These methods can be divided into three groups: for retrieving general information, for finding database capabilities, and for getting object descriptions.
  • 56. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 56 General Information The general information includes the URL, username, product name, product version, driver name, driver version, available functions, available data types and so on.
  • 57. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 57 Obtaining Database Capabilities The examples of the database capabilities are whether the database supports the GROUP BY operator, the ALTER TABLE command with add column option, supports entry-level or full ANSI92 SQL grammar.
  • 58. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 58 Obtaining Object Descriptions the examples of the database objects are tables, views, and procedures.
  • 59. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 59 DatabaseMetaData dbMetaData = connection.getMetaData(); System.out.println("database URL: " + dbMetaData.getURL()); System.out.println("database username: " + dbMetaData.getUserName()); System.out.println("database product name: " + dbMetaData.getDatabaseProductName()); System.out.println("database product version: " + dbMetaData.getDatabaseProductVersion()); System.out.println("JDBC driver name: " + dbMetaData.getDriverName()); System.out.println("JDBC driver version: " + dbMetaData.getDriverVersion()); System.out.println("JDBC driver major version: " + new Integer(dbMetaData.getDriverMajorVersion())); System.out.println("JDBC driver minor version: " + new Integer(dbMetaData.getDriverMinorVersion())); System.out.println("Max number of connections: " + new Integer(dbMetaData.getMaxConnections())); System.out.println("MaxTableNameLentgh: " + new Integer(dbMetaData.getMaxTableNameLength())); System.out.println("MaxColumnsInTable: " + new Integer(dbMetaData.getMaxColumnsInTable())); connection.close(); Examples Sample run on next slide
  • 60. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 60 Sample Run