Professional Documents
Culture Documents
Java Database
Romi Satria Wahono
romi@romisatriawahono.net
http://romisatriawahono.net
0878-804804-85
Materi
1. OOP Concepts:
Konsep dan Paradigma Object-Oriented
2. Java Fundamentals:
Memahami Sintaks dan Grammar Bahasa Java
3. Java GUI:
Swing, GUI Component, Event Handling,
Studi Kasus Aplikasi GUI
4. Java Advanced:
Eksepsi, Thread, Java API, Collection
5. Java Database:
Koneksi ke Database, Studi Kasus Aplikasi Dat
Java Database
1. Pengantar Database
2. Pengantar SQL
3. Koneksi Aplikasi Java ke Database
4. Studi Kasus Aplikasi Java Database
Pengantar Database
Introduction to Database
Database system is a computer based re
cord keeping system
It is a system whose overall purpose is to
record and maintain information that is
deemed important to the organization
Database is collection of stored operati
onal data which can be used and shared
by different applications and users of an
y organization
Why Database
Database system provides the organizatio
n with centralized control of its operation
al data, which is one of its most valuable a
ssets
This is totally opposite of the situation tha
t is happening in many organizations, whe
re typically each application has its own p
rivate files (flat file). This makes the operat
ional data widely dispersed and difficult t
o control
PRODUCT
VENDOR
DB2
Ingress
Oracle
Access
PostgreSQL
MySQL
2. Network
DMS100
IDMS
3. Heirarchical
IMS
System 2000
4. Object oriented
Starburst
Gemstone
Orion
IBMSQL/DS
Relational Tech.
Oracle corp
Microsoft
Unysis
Cullinet
IBM
Intel
IBM
Relational Database
Relational database is a collection of tabl
es
Formally a table is called a relation
Database is a structure that can hold infor
mation about tables, rows, and columns
Relational Database
Relational
Relational
l
Model
DBMS
Traditiona
File System
Relation
Table
File
Tuple
Row
Record
Attribute
Column
Field
Primary Key (PK) Primary Key (PK)
Search Ke
y
Relationship (FK) Relationship (FK)
Not Use
Relational Database
1. Primary Key (PK): An attribute which can
uniquely identify each record (tuple) of a
relation (table)
2. Foreign Key (FK): An attribute which is a r
egular attribute in one table but a primar
y key in another table
Attribute
Primary Key (PK)
Sale
SalesNO Name
10
12
48
Rate
James 10
Black
15
Black
8
Tuple (record)
City
Dept#
Dallas
A211
Denver
F654
WashDC A211
Example of a Relational
Database
Customer
CustID Name
132
135
198
Balance
Black
Tom
Tom
City
2000.00 Dallas
129.89 Denver
(132.90) Dallas
SaleNo
10
12
10
Rate
James 10
Black
15
Black
8
City
Dept#
Dallas
A211
Denver
F654
WashDC A211
Example of a Relational
Database
Customer
CustID Name
132
135
198
Black
Tom
Tom
Balance
City
2000.00
129.89
(132.90)
SaleNo
Dallas
Denver
Dallas
10
12
10
James 10
Black 15
Black
8
Dallas
A211
Denver
F654
WashDC A211
11/2/94
2/15/95
10/4/94
OrderLine
CustID SalesNO
132
135
102
Customer
CustID Name Balance
132 Black 2000.00
135 Tom
129.89
198 Tom
(132.90)
ONO Oline#
10
12
53
102
102
199
City
Dallas
Denver
Dallas
SaleNo
10
12
10
1
2
1
Part#
Qty
12.00 10
129.89 1
32.90 3
Part#
EX454
DE012
DC810
Sales
SalesNO Name
10
12
48
James
Black
Black
Rate
10
15
8
City
Dept#
Dallas
A211
Denver
F654
WashDC A211
Functionality of a DBMS
The programmer sees SQL, which has two co
mponents:
1. Data Definition Language (DDL)
2. Data Manipulation Language (DML)
Query engine
Query optimizer
Storage management
Transaction Management (concurrency, recovery)
Transactions
Enroll Mary Johnson in CSE444:
BEGIN
BEGINTRANSACTION;
TRANSACTION;
INSERT
INSERTINTO
INTOTakes
Takes
SELECT
SELECTStudents.SSN,
Students.SSN,Courses.CID
Courses.CID
FROM
FROMStudents,
Students,Courses
Courses
WHERE
WHEREStudents.name
Students.name=
=Mary
MaryJohnson
Johnsonand
and
Courses.name
Courses.name=
=CSE444
CSE444
----More
Moreupdates
updateshere....
here....
IF
IFeverything-went-OK
everything-went-OK
THEN
THENCOMMIT;
COMMIT;
ELSE
ELSEROLLBACK
ROLLBACK
If system crashes, the transaction is still either committed or aborted
Transactions
A transaction = sequence of statements
that either all succeed, or all fail
Transactions have the ACID properties:
1. A = atomicity (a transaction should be done or undone comple
tely )
Queries
Find all courses that Mary takes
SELECT
SELECT
FROM
FROM
WHERE
WHERE
C.name
C.name
Students
Students S,
S, Takes
Takes T,
T, Courses
Courses CC
S.name=Mary
S.name=Mary and
and
S.ssn
S.ssn =
= T.ssn
T.ssn and
and T.cid
T.cid =
= C.cid
C.cid
SELECT
SELECT C.name
C.name
FROM
FROMStudents
StudentsS,
S,Takes
TakesT,
T,Courses
CoursesCC
WHERE
WHERES.name=Mary
S.name=Maryand
and
S.ssn
S.ssn=
=T.ssn
T.ssnand
andT.cid
T.cid=
=C.cid
C.cid
cid=cid
sid=sid
name=Mary
Students
Takes
Courses
Pengantar SQL
SQL Introduction
Standard language for querying and manip
ulating data
SQL = Structured Query Language
Many standards out there:
ANSI SQL
SQL92 (a.k.a. SQL2)
SQL99 (a.k.a. SQL3)
Vendors support various subsets of these
What we discuss is common to all of them
SQL
Data Definition Language (DDL)
Create/alter/delete tables and their attributes
Transact-SQL
Idea: package a sequence of SQL statements server
CHAR(20)
-- fixed length
VARCHAR(40)
-- variable length
Numbers:
DATE
DATETIME
-- SQL Server
Tables in SQL
Attribute names
Table name
Product
PName
Price
Category
Manufacturer
Gizmo
$19.99
Gadgets
GizmoWorks
Powergizmo
$29.99
Gadgets
GizmoWorks
SingleTouch
$149.99
Photography
Canon
MultiTouch
$203.99
Household
Hitachi
Tuples or rows
Tables Explained
A tuple = a record
Restriction: all attributes are of atomic type
Tables Explained
The schema of a table is the table name an
d its attributes:
Product(PName, Price, Category, Manfactur
er)
A key is an attribute whose values are uniqu
e;
we underline a key
Product(PName, Price, Category, Manfactur
er)
SQL Query
Basic form: (plus many many more bells and whistles)
SELECT
SELECT
FROM
FROM
WHERE
WHERE
attributes
attributes
relations
relations (possibly
(possibly multiple,
multiple, joined)
joined)
conditions
conditions (selections)
(selections)
Price
Category
Manufacturer
Gizmo
$19.99
Gadgets
GizmoWorks
Powergizmo
$29.99
Gadgets
GizmoWorks
SingleTouch
$149.99
Photography
Canon
MultiTouch
$203.99
Household
Hitachi
PName
Price
Category
Manufacturer
Gizmo
$19.99
Gadgets
GizmoWorks
Powergizmo
$29.99
Gadgets
GizmoWorks
Product
SELECT
SELECT
FROM
FROM
WHERE
WHERE
**
Product
Product
category=Gadgets
category=Gadgets
selection
SELECT
SELECT
FROM
FROM
WHERE
WHERE
PName
Price
Category
Manufacturer
Gizmo
$19.99
Gadgets
GizmoWorks
Powergizmo
$29.99
Gadgets
GizmoWorks
SingleTouch
$149.99
Photography
Canon
MultiTouch
$203.99
Household
Hitachi
PName,
PName,Price,
Price,Manufacturer
Manufacturer
Product
Product
Price
Price>
>100
100
selection and
projection
PName
Price
Manufacturer
SingleTouch
$149.99
Canon
MultiTouch
$203.99
Hitachi
PName,
PName,Price,
Price,Manufacturer
Manufacturer
Product
Product
Price
Price>
>100
100
Selections
What goes in the WHERE clause:
x = y, x < y, x <= y, etc
For number, they have the usual meanings
For CHAR and VARCHAR: lexicographic ordering
Expected conversion between CHAR and VARCHAR
SELECT
SELECT
FROM
FROM
WHERE
WHERE
**
Products
Products
PName
PNameLIKE
LIKE%gizmo%
%gizmo%
Eliminating Duplicates
Category
SELECT
SELECT
FROM
FROM
category
category
Product
Product
Gadgets
Gadgets
Photography
Household
Compare to:
Category
SELECT
SELECT
FROM
FROM
DISTINCT
DISTINCTcategory
category
Product
Product
Gadgets
Photography
Household
SELECT
SELECT pname,
pname,price,
price,manufacturer
manufacturer
FROM
FROM Product
Product
WHERE
WHERE category=gizmo
category=gizmoAND
ANDprice
price>
>50
50
ORDER
ORDERBY
BY price,
price,pname
pname
PName
Price
Category
Manufacturer
Gizmo
$19.99
Gadgets
GizmoWorks
Powergizmo
$29.99
Gadgets
GizmoWorks
SingleTouch
$149.99
Photography
Canon
MultiTouch
$203.99
Household
Hitachi
SELECT
SELECT DISTINCT
DISTINCT
category
category
FROM
FROM Product
Product
ORDER
ORDERBY
BYcategory
category
Gadgets
Household
Photography
Compare to:
SELECT
SELECT DISTINCT
DISTINCT
category
category
FROM
FROM Product
Product
ORDER
ORDERBY
BYPName
PName
Joins in SQL
Connect two or more tables:
Product
PName
Price
Category
Manufacturer
Gizmo
$19.99
Gadgets
GizmoWorks
Powergizmo
$29.99
Gadgets
GizmoWorks
SingleTouch
$149.99
Photography
Canon
MultiTouch
$203.99
Household
Hitachi
Company
What is
the Connection
between
them ?
CName
StockPrice
Country
GizmoWorks
25
USA
Canon
65
Japan
Hitachi
15
Japan
Joins
Join
between Product
and Company
SELECT
SELECT PName,
PName, Price
Price
FROM
Product,
FROM
Product, Company
Company
WHERE
WHERE Manufacturer=CName
Manufacturer=CName AND
AND
Country=Japan
Country=Japan
AND
AND Price
Price <=
<= 200
200
Joins in SQL
Product
Company
PName
Price
Category
Manufacturer
Cname
StockPrice
Country
Gizmo
$19.99
Gadgets
GizmoWorks
GizmoWorks
25
USA
Powergizmo
$29.99
Gadgets
GizmoWorks
Canon
65
Japan
SingleTouch
$149.99
Photography
Canon
Hitachi
15
Japan
MultiTouch
$203.99
Household
Hitachi
SELECT
SELECT
FROM
FROM
WHERE
WHERE
PName,
PName,Price
Price
Product,
Company
Product, Company
Manufacturer=CName
Manufacturer=CNameAND
ANDCountry=Japan
Country=Japan
AND
Price
<=
200
AND Price <= 200
PName
Price
SingleTouch
$149.99
Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all countries that manufacture some product in the Gadgets
category.
SELECT
SELECT
FROM
FROM
WHERE
WHERE
Country
Country
Product,
Product, Company
Company
Manufacturer=CName
Manufacturer=CName AND
AND Category=Gadgets
Category=Gadgets
Joins in SQL
Product
Company
PName
Price
Category
Manufacturer
Gizmo
$19.99
Gadgets
GizmoWorks
Powergizmo
$29.99
Gadgets
GizmoWorks
SingleTouch
$149.99
Photography
Canon
MultiTouch
$203.99
Household
Hitachi
SELECT
SELECT
FROM
FROM
WHERE
WHERE
Cname
StockPrice
Country
GizmoWorks
25
USA
Canon
65
Japan
Hitachi
15
Japan
Country
Country
Product,
Product,Company
Company
Manufacturer=CName
Manufacturer=CNameAND
ANDCategory=Gadgets
Category=Gadgets
Country
What is
the problem ?
Whats the
solution ?
??
??
Joins
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Person(persname, phoneNumber, city)
Find names of people living in Seattle that bought some
product in the Gadgets category, and the names of the
stores they bought such product from
SELECT
SELECT
FROM
FROM
WHERE
WHERE
AND
AND
DISTINCT
DISTINCTpersname,
persname,store
store
Person,
Person,Purchase,
Purchase,Product
Product
persname=buyer
persname=buyerAND
ANDproduct
product=
=pname
pname
city=Seattle
city=Seattle AND
ANDcategory=Gadgets
category=Gadgets
Disambiguating Attributes
Sometimes two relations have the same attribute:
Person(pname, address, worksfor)
Company(cname, address)
SELECT
SELECT
FROM
FROM
WHERE
WHERE
SELECT
SELECT
FROM
FROM
WHERE
WHERE
DISTINCT
DISTINCTpname,
pname,address
address
Person,
Person,Company
Company
worksfor
worksfor=
=cname
cname
Which
address ?
DISTINCT
DISTINCTPerson.pname,
Person.pname,Company.address
Company.address
Person,
Person,Company
Company
Person.worksfor
Person.worksfor=
=Company.cname
Company.cname
Tuple Variables
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Person(persname, phoneNumber, city)
Find all stores that sold at least one product that the store
BestBuy also sold:
SELECT
SELECTDISTINCT
DISTINCT x.store
x.store
FROM
FROM Purchase
PurchaseAS
ASx,
x,Purchase
PurchaseAS
ASyy
WHERE
WHERE x.product
x.product=
=y.product
y.productAND
ANDy.store
y.store=
=BestBuy
BestBuy
Answer (store)
Tuple Variables
General rule:
tuple variables introduced automatically by the system:
Product ( name, price, category, manufacturer)
SELECT
SELECT name
name
FROM
FROM Product
Product
WHERE
WHERE price
price>
>100
100
Becomes:
SELECT
SELECTProduct.name
Product.name
FROM
FROM Product
ProductAS
ASProduct
Product
WHERE
WHEREProduct.price
Product.price>
>100
100
Renaming Columns
Product
SELECT
SELECT
FROM
FROM
WHERE
WHERE
PName
Price
Category
Manufacturer
Gizmo
$19.99
Gadgets
GizmoWorks
Powergizmo
$29.99
Gadgets
GizmoWorks
SingleTouch
$149.99
Photography
Canon
MultiTouch
$203.99
Household
Hitachi
Pname
PnameAS
ASprodName,
prodName,Price
PriceAS
ASaskPrice
askPrice
Product
Product
Price
Price>
>100
100
Query with
renaming
prodName
askPrice
SingleTouch
$149.99
MultiTouch
$203.99
MySQL
PostgreSQL
Oracle
DriverManager
user
select
passwor
d
Connection
host
Statement
update
database
create
ResultSet
url
insert
Java application
{ ...
"SELECT ... FROM ... WHERE"
... }
DBMS
JDBC Drivers
Java
application
JDBC-API
JDBCDriver manager
Native
Protocol driver
JDBCNet-driver
JDBC-ODBC
bridge
Native
API-driver
DBMiddleware
ODBC
Client library
Client library
Task
Initialisation
Load driver
Create connection
DriverManager
Connection
Processing
Statement
ResultSet etc.
Termination
Terminate connection
Release data structures
Connection
Statement etc.
import java.sql.*;
public class jdbctest {
public static void main(String args[]){
try{
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection
("jdbc:postgresql://lsir-cis-pc8:5401/pcmdb", "user", "passwd
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("select name, number from pcmtable where number < 2");
while(rs.next())
System.out.println(rs.getString(1) + " (" + rs.getInt(2) +
stmt.close()
con.close();
} catch(Exception e){
System.err.println(e);
}
}}
Loading of Driver
Creates an instance of the driver
Registers driver in the driver manag
er
Explicit loading
String l_driver = "org.postgresql.Dri
ver";
Class.forName(l_driver);
Several drivers can be loaded and r
egistered
Addressing Database
A connection is a session with one data
base
Databases are addressed using a URL o
f the form "jdbc:<subprotocol>:<subna
me>"
Examples
jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database
Defaults: host=localhost, port=5432
Connecting to Database
Connection is established
Connection con = DriverManager.getConnecti
on(URL,USERID,PWD);
Aplikasi Database
Aplikasi Telepon
Aplikasi Mahasiswa
Aplikasi Bank
Aplikasi Penjualan Barang
Aplikasi Telepon
1. Ekstrak xampplite dan jalankan xampp_start.e
xe untuk mengaktifkan Apache dan MySQL
2. Buka browser, arahkan url ke http://localhost
dan klik link ke phpMyAdmin
3. Buat database telepon
4. Buat satu table bukutelepon, yang berisi field
dengan id sebagai primary key (PK):
1.
2.
3.
4.
5.
id
integer (auto increment)
nama
varchar(20)
alamat
varchar(50)
telepon
varchar(20)
handphone
varchar(20)
Aplikasi Telepon
Extract dan copy folder 05 JAVA DATABASE
nim
nama
kota
handphone
status
kelas
konsentrasi
Tugas
Pahami program yang ada di package dbgui.m
ysql
Buat empat class java GUI yang melakukan ko
neksi dan query ke database mahasiswa:
1. MahasiwaInsert.java
2. MahasiswaRead.java
3. MahasiswaUpdate.java
4. MahasiswaDelete.java
5. MenuUtama.java
Tugas
Kerjakan semua latihan dan tugas yang ad
a di slide Java Database
Kirimkan netbeans project yang sudah di
zip ke romi@brainmatics.com
dengan subyek: [OOP4-Universitas] Nam
aNIM
Deadline: 1 minggu
Meng-copy file orang lain akan menyebab
kan nilai tugas 0
UAS
Kembangkan aplikasi java berbasis GUI yang mengakses data
base MySQL. Fitur utama dari aplikasi adalah kemampuan un
tuk CRUD (create, read (listing), update, delete) data dari dat
abase MySQL dan fitur transaksi serta reporting. Gunakan le
bih dari satu table
Penjualan
6. Aplikasi
Sewa
Apartemen
1.
PilihAplikasi
aplikasi
dari listBuku
di bawah (digit
terakhir
NIM):
2.
3.
4.
5.
7.
8.
9.
0.
Aplikasi Sewa PC
Aplikasi Penjualan Handphone
Aplikasi Penjualan CD Musik
Aplikasi Penjualan Notebook
Tugas
Kembangkan aplikasi java berbasis GUI yang mengakses data
base MySQL. Fitur utama dari aplikasi adalah kemampuan un
tuk CRUD (create, read (listing), update, delete) data dari dat
abase MySQL dan fitur transaksi serta reporting. Gunakan le
bih dari satu table
Penjualan
6. Aplikasi
Rental
DVD
1.
PilihAplikasi
aplikasi
dari listBuku
di bawah (digit
terakhir
NIM):
2.
3.
4.
5.
7.
8.
9.
0.
Deadline: 2 Minggu
Nyontek akan diberi nilai 0
Referensi
1. Sharon Zakhour et al, The Java Tutorial Fourth E
dition, http://java.sun.com/docs/books/tutorial
2. Cay Horstmann, Big Java, John Wiley & Sons, 201
0
3. Rogers Cadenhead & Laura Lemay, Teach Yoursel
f Java 6 in 21 Days, Sams Publishing, 2007
4. Deitel & Deitel, Java for Programmers, Prentice H
all, 2009
5. Robert Lafore, Data Structures and Algorithms in
Java Second Edition, Sams Publishing, 2003
6. Tim Pengembang JENI, JENI 1-6, Depdiknas, 200
7
7. Rachmad Hakim & Sutarto, Mastering Java, Elex