Sei sulla pagina 1di 185



POUL KLAUSEN

JAVA 6: JDBC
AND DATABASE
APPLICATIONS
SOFTWARE DEVELOPMENT

2
Java 6: JDBC and database applications: Software Development
1st edition
© 2017 Poul Klausen & bookboon.com
ISBN 978-87-403-1736-7
Peer review by Ove Thomsen, EA Dania

3
JAVA 6: JDBC AND DATABASE APPLICATIONS Contents

CONTENTS
Foreword 6

1 Introduction 8
About surrogate keys 10

2 JDBC 11
2.1 HelloJDBC 11
Exercise 1 14

3 Database operations 15
3.1 SQL statements 15
Exercise 2 20

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

4
JAVA 6: JDBC AND DATABASE APPLICATIONS Contents

4 ResultSet 22
4.1 Update a ResultSet 25
4.2 Municipalities and zipcodes 29
Exercise 3 35
Problem 1 35
4.3 Stored procedures 37

5 Data types 40

6 Transactions 47
6.1 Bach updates 51
Exercise 4 53

7 The component JTable 54


7.1 The demo program 55
Problem 2 90

8 Files in databases 92
Exercise 5 96

9 DDL commands 97

10 Final examples 99
10.1 World 99
10.2 MyWines 107

Appendix A: Install MySQL 140

Appendix B 148

5
JAVA 6: JDBC AND DATABASE APPLICATIONS Foreword

FOREWORD
This book is the sixth in a series of books on software development. The programming language
is Java, and the language and its syntax and semantics fills obviously much, but the books
have also largely focus on the process and how to develop good and robust applications.
The subject of the current book is database applications, and how to write programs in Java
that uses a database. In practice, programs that requiring many data transactions always uses
databases, and the development of database applications is an important issue and necessary
knowledge to work professionally as a software developer. In principle, it is simple, and a
good piece of the road is just a question of accepting that you should write as shown in the
book’s examples, but database programming requires knowledge of SQL, and the hardest
part is actually to write SQL statements correctly. Therefore, the book has an appendix that
provides a quick introduction to SQL and describes the most basic syntax. In addition to
SQL it is a prerequisite, to try out the book’s examples and solve the book’s exercises, that
the reader has a running database, and MySQL will be used. The book has an appendix
that shows how to install MySQL.

As the title says this series of books deals with software development, and the goal is to
teach the reader how to develop applications in Java. It can be learned by reading about
the subject and by studying complete sample programs, but most importantly by yourself
to do it and write your own programs from scratch. Therefore, an important part of the
books is exercises and problems, where the reader has to write programs that correspond to
the substance being treated in the books. All books in the series is built around the same
skeleton and will consist of text and examples and exercises and problems that are placed
in the text where they naturally belongs. The difference between exercises and problems is
that the exercises largely deals with repetitions of the substance that is presented in the text,
and furthermore it is relatively accurately described what to do. Problems are in turn more
loosely described, and are typically a little bigger and there is rarely any clear best solution.
These are books to be read from start to finish, but the many code examples, including
exercises and problems plays a central role, and it is important that the reader predict in
detail studying the code to the many examples and also solves the exercises and problems
or possibly just studying the recommended solutions.

6
JAVA 6: JDBC AND DATABASE APPLICATIONS Foreword

All books ends with one or two larger sample programs, which focus primarily is on process
and an explanation of how the program is written. On the other hand appears the code only
to a limited extent – if at all – and the reader should instead study the finished program
code perhaps while testing the program. In addition to show the development of programs
that are larger than the examples, which otherwise is presented, the aim of the concluding
examples also is to show program examples from varying fields of application.

Most books also ends with an appendix dealing with a subject that would not be treated
in the books. It may be issues on the installation of software or other topics in computer
technology, which are not about software development, but where it is necessary to have
an introductory knowledge. If the reader already is familiar with the subject, the current
appendix can be skipped.

The programming language is, as mentioned Java, and besides the books use the following
products:

-- NetBeans as IDE for application development


-- MySQL to the extent there is a need for a database server (from the book Java 6
onwards)
-- GlassFish as a web server and application server (from the book Java 11 onwards)

It is products that are free of charge and free to install, and there is even talk about products,
where the installation is progressing all by itself and without major efforts and challenges.
In addition, there are on the web detailed installation instructions for all the three products.
The products are available on Windows and Linux, and it therefore plays no special role if
you use Linux or Windows.

All sample programs are developed and tested on machines running Linux. In fact, it plays
no major role, as both Java and other products work in exactly the same way whether the
platform is one or the other. Some places will be in the books where you could see that
the platform is Linux, and this applies primarily commands that concerning the file system.
Otherwise it has no meaning to the reader that the programs are developed on a Linux
machine, and they can immediately also run under Windows unless a program refers to
the file system where it may be necessary to change the name of a file.

Finally a little about what the books are not. It is not “how to write” or for that matter
reference manuals in Java, but it is as the title says books on software development. It is
my hope that the reader when reading the books and through the many examples can find
inspiration for how to write good programs, but also can be used as a source collection
with a number of examples of solutions to concrete everyday programming problems that
you regularly face as a software developer.

7
JAVA 6: JDBC AND DATABASE APPLICATIONS Introduction

1 INTRODUCTION
Many applications need to use and maintain persistent data. In the preceding books, I have
solved such tasks by using object serialization or plain text files, which indeed in some cases
can be an excellent solution, but if there are large amounts of data with frequent updates,
or data where multiple users must have access to the data, it is not a viable option. In these
cases – and in practice, almost always – data are stored in databases.

A database is a collection of files that contains related data of one or another business,
but it’s a lot more because it is a software package that consists of programs that manages
and maintains the database system’s databases. This software package is called a database
management system, and by a database system is meant partly the management system as
well as the databases that the system maintains.

In this book I will address key concepts related to databases, but as the other of the books
seen by a programmer, and thus especially what a programmer needs to know. The subject
requires a specific database management system, and I will use MySQL. In fact, the system is
not so important, but MySQL is available in an open source version that can be downloaded
and installed for free. MySQL is today a powerful database system that supports all the
services that one would expect from a good database management system, and besides
MySQL is a widely used system in practice. In order to use MySQL from a Java program,
you must at least install three products:

1. the database management system it self, that is the MySQL server


2. a program called MySQL Workbench, that the user can use to manage the system
3. a class library called JDBC, which makes it possible to write Java applications that
uses databases

The book’s appendix A shows how these products can be installed on the machine.

The following is based on two assumptions:

1. that you have a running MySQL server installed with the above products (see
appendix A for how to install the products)
2. you have an introductory knowledge of SQL and know the most common statements
(see appendix B for an introduction).

8
JAVA 6: JDBC AND DATABASE APPLICATIONS Introduction
JAVA 6: JDBC AND DATABASE APPLICATIONS IntroduCtIon

To show how to use databases from a Java program, you must also have a database. Open
To show how to use databases from a Java program, you must also have a database. Open
MySQL Workbench (see below). Perform then the command that is entered. You do this by
MySQL Workbench (see below). Perform then the command that is entered. You do this by
clicking on the third icon (lightning) in the toolbar. The result is the creation of a database
clicking on the third icon (lightning) in the toolbar. The result is the creation of a database
with the name padata. You may of course choose a different name if you wish, but it makes
with the name padata. You may of course choose a different name if you wish, but it makes
it easier to follow the book’s examples and exercises if you choose the same name, which I
it easier to follow the book’s examples and exercises if you choose the same name, which I
have used. So far, it is an empty database, but through the book I will create several tables
have used. So far, it is an empty database, but through the book I will create several tables
with data.
with data.

The folder to this book contains a SQL script called CreateHistorie.sql. Open this script in
The folder to this book contains a SQL script called CreateHistorie.sql. Open this script in
MySQL Workbench. The contents are as shown below:
MySQL Workbench. The contents are as shown below:

use padata;
drop table if exists history;

create table history


(
id int not null auto_increment primary key, # autogenerated surrogat key
name varchar(50) not null, # the person's name
title varchar(30), # the person's title
birth int, # birth, start of reign, or equivalent
death int, # death, end of reign, or equivalent
country char(2), # the country the person comes from
description text # a description
);

9
9
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS IntroduCtIon
Introduction

ItIt isis aa script


script that
that creates
creates aa table
table with
with information
information aboutabout historical
historical persons.
persons. AA table
table consists
consists ofof
rowsand
rows andcolumns,
columns,and andeach
eachrowrowcontains
containsdata
data(information)
(information)aboutaboutaaparticular
particularperson.
person.AAcolumn
column
has aa type
has type andand aa name.
name. The
The name
name makes
makes itit possible
possible to to refer
refer to
to the
the column
column in in SQL
SQL statements,
statements,
while the
while the type
type determines
determines whatwhat kind
kind of
of values
values thethe column
column can can hold.
hold. Taking
Taking thethe above
above script,
script,
indicating the
indicating the first
first column,
column, that
that the
the column
column must
must contain
contain an an auto-generated
auto-generated integer
integer that
that starts
starts
with 11 and
with and increases
increases by
by 11 each
each time
time adding
adding aa row
row toto the
the table.
table. InIn addition
addition isis definied
definied that
that the
the
column must
column must be be the
the primary
primary key,
key, which
which means
means that
that the
the column’s
column’s values
values must
must be be unique
unique andand
thus can
thus can serve
serve toto identify
identify each
each row.
row. The
The next
next two
two columns
columns are are ofof the
the type
type varchar,
varchar, indicating
indicating
that the
that the column
column can can contain
contain aa string,
string, which
which inin this
this case
case must
must be be maximum
maximum of, of, respectively
respectively 50 50
and 30
and 30 characters.
characters. The The next
next two
two columns
columns again
again may
may contain
contain integers,
integers, andand the
the column
column withwith
the name
the name country
country mustmust contain
contain aa string
string of
of 22 characters.
characters. Finally,
Finally, thethe last
last column
column can can contain
contain
any text
any text (however,
(however, maximum
maximum 6553565535 characters).
characters). The
The column
column namename isis defined
defined notnot null,
null, which
which
means that
means that every
every row
row must
must have
have aa value
value in
in that
that column.
column. The The other
other columns
columns (except
(except thethe first
first
that isis the
that the primary
primary key)
key) does
does not
not need
need to
to have
have aa value,
value, but
but may
may be be null.
null.

The book’s
The book’s directory
directory also
also contains
contains aa script
script InsertHistory.sql
InsertHistory.sql where
where below
below shows
shows aa few
few lines
lines

use padata;
insert into history (name, death, title, country) values
('Gorm den Gamle', 958, 'King', 'DK');
insert into history (name, birth, death, title, country) values
('Harald Blåtand', 958, 987, 'King', 'DK');
...

IfIf you
you opens
opens the
the script
script in
in MySQL
MySQL Workbench
Workbench and
and executes
executes it,it, the
the script
script adds
adds 52
52 rows
rows to
to
the table history, where the rows contains data about Danish kings. The
the table history, where the rows contains data about Danish kings. The following assumesfollowing assumes
that
that this
this table
table isis created,
created, and
and the
the script
script InsertHistory.sql
InsertHistory.sql isis performed.
performed.

ABOUT
ABOUT SURROGATE
SURROGATE KEYS
KEYS
When
When you you have
have to
to create
create (design)
(design) aa database
database table,
table, you you must
must choose
choose one one oror more
more columns
columns
that
that can be used as the primary key (above id ). This means that each row must have a unique
can be used as the primary key (above id ). This means that each row must have a unique
value
value in this column or columns. Is it not possible, you can define a column, which then
in this column or columns. Is it not possible, you can define a column, which then
isis assigned
assigned a unique value, and it is the case of the column id of the table history, when the
a unique value, and it is the case of the column id of the table history, when the
value is automatically incremented by 1 each time you add a row
value is automatically incremented by 1 each time you add a row to the table. This column to the table. This column
can
can therefore
therefore be be used
used asas the
the primary
primary key, key, and
and itit isis called
called aa surrogate
surrogate key key corresponding
corresponding to, to,
that it is a replacement for another key column. Actually one
that it is a replacement for another key column. Actually one should, if possible, avoid should, if possible, avoid
surrogate
surrogate keys keys asas they
they expand
expand thethe table
table with
with data
data thatthat does
does notnot tell
tell anything,
anything, and and in
in this
this
case
case one might avoid the key as the Kings have unique names and thus the name could be
one might avoid the key as the Kings have unique names and thus the name could be
used
used as the primary key. When I have nonetheless chosen a surrogate key, it is because aa
as the primary key. When I have nonetheless chosen a surrogate key, it is because
string
string –– aa column
column of of the
the type
type varchar
varchar –– not not always
always isis aa good
good candidate
candidate for for aa primary
primary key,
key,
first,
first, it may be difficult to enter (you can misspell) and partly it is less effective than an int.
it may be difficult to enter (you can misspell) and partly it is less effective than an int.

10
10
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS JdBC
JDBC

2 JDBC
2 JDBC
JDBC is
JDBC is aa family
family of
of classes
classes that
that implements
implements an an interfaces
interfaces defined
defined inin the
the JDBC
JDBC API,
API, and
and
which makes
which makes itit possible,
possible, that
that aa Java
Java program
program cancan communicate
communicate with
with aa database
database server.
server. In
In
relation to
relation to the
the Java
Java program
program thethe API
API has
has the
the necessary
necessary types
types as
as interfaces
interfaces and
and classes
classes defined
defined
in the
in the package
package java.sql,
java.sql, while
while the
the specific
specific types
types are
are implemented
implemented by by aa JDBC
JDBC driver.
driver. So
So there
there
has to
has to be
be aa JDBC
JDBC driver
driver available
available for
for each
each of
of the
the databases
databases that
that the
the program
program must
must apply
apply and
and
often itit is
often is the
the database
database supplier
supplier that
that develops
develops the
the JDBC
JDBC driver.
driver. You
You can
can think
think of
of aa JDBC
JDBC
driver as
driver as aa layer
layer between
between the
the database
database and
and the
the Java
Java program
program that
that ensures
ensures that
that the
the program
program
can use
can use the
the database
database in
in the
the same
same way,
way, whether
whether itit is
is one
one or
or the
the other
other database
database system.
system.

2.1 HELLOJDBC
2.1 HELLOJDBC
Before II go
Before go further
further and
and look
look at
at the
the details
details concerning
concerning JDBC,
JDBC, II will
will look
look at
at an
an example
example to
to
show that
show that itit is
is quite
quite easy
easy to
to use
use aa database
database from
from aa Java
Java program.
program. The
The following
following program
program
reads the
reads the rows
rows in in the
the table
table history
history and
and prints
prints them
them on
on the
the screen:
screen:

package hellojdbc;

import java.sql.*;

public class HelloJDBC


{
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
try
{
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234");
stmt = conn.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM history");
while(res.next())
{
String name = res.getString("name");
String title = res.getString("title");
int birth = res.getInt("birth");
int death = res.getInt("death");
String country = res.getString("country");
System.out.printf("%-25s%-10S%5d%5d %s\n", name, title, birth,
death, country);
}
}

11
11
JAVA 6: JDBC AND DATABASE APPLICATIONS JDBC
JAVA 6: JDBC AND DATABASE APPLICATIONS JdBC

catch(SQLException ex)
{
System.out.println(ex);
}
catch(Exception ex)
{
System.out.println(ex);
}
finally
{
try
{
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
catch (SQLException ex)
{
System.out.println(ex);
}
}
}
}

www.job.oticon.dk

12
12
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS JDBC
JdBC
JAVA 6: JDBC AND DATABASE APPLICATIONS JdBC

You
You must
must add
add an
an import
import statement
statement to
to the
the necessary
necessary types:
types:
You must add an import statement to the necessary types:

import java.sql.*;
import java.sql.*;

Then
Then you
you must
must define
define aaa connection
connection to
to the
the database:
database:
Then you must define connection to the database:

conn = DriverManager.getConnection(
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234");
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234");

Writing this
Writing
Writing this connection
this connection isis
connection is in
in fact
in fact the
fact the only
the only difficulty
only difficulty of
difficulty of writing
of writing database
writing database applications,
database applications, as
applications, as itit
as it
should be
should
should be written
be written correctly
written correctly and
correctly and as
and as itit
as it depends
depends on
depends on the
on the specific
the specific database
specific database product.
database product. The
product. The method
The method
method
getConnection() has three
getConnection() three parameters. The The first isis aa connection
connection string, while
while the last
last two are
are
getConnection() has
has three parameters.
parameters. The first first is a connection string,
string, while the
the last two
two are
respectively the
respectively
respectively the username
the username and
username and the
and the password
the password to
password to the
to the database.
the database. In
database. In this
In this case,
this case, they
case, they are
they are direct
are direct
direct
encoded as
encoded
encoded as strings,
as strings, and
strings, and itit
and it may
may of
may of course
of course not
course not be
not be the
be the solution
the solution to
solution to an
to an application
an application which
application which isis
which is used
used
used
in an
in
in an operation
an operation condition,
operation condition, but
condition, but about
but about this
about this later.
this later. Connection
later. Connection string
Connection string consists
string consists of
consists of the
of the database
the database
database
server that here
server here is a MySQL server server on the the local machine:
machine:
server that
that here isis aa MySQL
MySQL server on on the local
local machine:

jdbc:mysql://localhost
jdbc:mysql://localhost

This is
This is followed
followed byby the
the port
port number
number (which
(which incidentally
incidentally isis not
not necessary,
necessary, since
since 3306
3306 is
This is followed by the port number (which incidentally is not necessary, since 3306 isis
the default
the default port
port number
number forfor MySQL),
MySQL), and and finally
finally follows
follows the
the name
name ofof the
the database,
database, which
which
the default port number for MySQL), and finally follows the name of the database, which
here is
here is padata.
padata. In
In this
this case,
case, there
there is
is also
also provided
provided an an information
information that
that the
the database
database does
does
here is padata. In this case, there is also provided an information that the database does
not require an SSL connection. If you need to use a database on another machine, you
not require
not require anan SSL
SSL connection.
connection. If If you
you need
need to
to use
use aa database
database on
on another
another machine,
machine, youyou
must type
must type something
type something else
something else than
else than localhost
than localhost (possible
localhost (possible an
(possible an IP)
an IP) and
IP) and you
and you may
you may also
may also need
also need to
need to use
to use
use
must
a different
different port
port number.
number. Finally,
Finally, be
be aware
aware that
that the
the connection
connection string
string looks
looks different
different if is
aa different port number. Finally, be aware that the connection string looks different ifif isis
another database
another database than
than MySQL.
MySQL.
another database than MySQL.

After the
After the connection
connection is is defined
defined thethe program
program creates
creates ofof aa Statement,
Statement, which
which isis an
an object
object that
that
After the connection is defined the program creates of a Statement, which is an object that
represents aa SQL
represents SQL statement,
statement, and and the
the statement
statement is executed
executed by by the
the method
method executeQuery(),
executeQuery(),
represents a SQL statement, and the statement isis executed by the method executeQuery(),
wherein the
wherein the parameter
parameter is is a SQL
SQL SELECT
SELECT command.
command. The The result
result of
of this
this method
method is a ResultSet,
ResultSet,
wherein the parameter is aa SQL SELECT command. The result of this method isis aa ResultSet,
which is a collection with an object for each of the rows, the SQL command has extracted
which isis aa collection
which collection with
with an an object
object for
for each
each of
of the
the rows,
rows, the
the SQL
SQL command
command has has extracted
extracted
from
from the the database.
the database. After
database. After
After thethe statement
the statement is successful
statement isis successful excuted,
successful excuted,
excuted, thethe application
the application performs aaa
performs
application performs
from
loop that
loop that iterates
iterates over
over the
the rows,
rows, and
and for
for each
each row
row prints
prints aa line
line with
with the
the values
values of
of the
the row’s
row’s
loop that iterates over the rows, and for each row prints a line with the values of the row’s
fields and
fields and thus
thus the
the values
values in in each
each column.
column. YouYou should
should note,
note, how
how toto refer
refer to
to values
values using
using
fields and thus the values in each column. You should note, how to refer to values using
methods in the class ResultSet and the column names from the database.
methods in
methods in the
the class
class ResultSet
ResultSet andand the
the column
column names
names from
from thethe database.
database.

The most
The most database
database operations
operations can
can raise
raise a SQLException,
SQLException, so
so the
the statements
statements are
are placed
placed in
in aa
The most database operations can raise aa SQLException, so the statements are placed in a
try block.
try block. The
block. The associated
The associated finally
associated finally block
finally block closes
block closes the
closes the Statement
the Statement and
Statement and the
and the Connection,
the Connection, and
Connection, and it is
and itit isis
try
important to release the resources allocated.
important to
important to release
release the
the resources
resources allocated.
allocated.

13
13
13
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS JDBC
JdBC

IfIf you
you executes
executes the
the program,
program, you
you get
get the
the following
following result,
result, where
where II have
have only
only shown
shown the
the
first
firstlines:
lines:

Gorm den Gamle KING 0 958 DK


Harald Blåtand KING 958 987 DK
Svend Tveskæg KING 987 1014 DK
Harad d. 2. KING 1014 1018 DK
Knud den Store KING 1018 1035 DK

As
As isis apparent
apparent from
from this
this example,
example, itit isis basically
basically simple
simple toto perform
perform aa data
data operation
operation from
from
aaJava
Javaprogram.
program.Of Ofcourse
coursethere
thereisismore
moretototell tellthan
thanthis
thisexample
exampleshows,
shows,andandthe
thethe
thenext
next
chapter
chaptershows
showsmany
manyother
otherexamples,
examples,but butthe thedifferences
differencesare
areconcerning
concerningSQLSQLactually
actuallymuch
much
more
morethan thanJava.
Java.

EXERCISE
EXERCISE11
You
You must
must write
write aa program
program that
that looks
looks like
like HelloJDBC,
HelloJDBC, but
but the
the program
program should
should only
only print
print
the
the name
name and
and the
the years
years and
and only
only for
for those
those persons
persons who
who are
are either
either kings
kings or
or queens,
queens, and
and
whose
whosereign
reignstarts
startsbefore
before1500.
1500.

1414
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS dataBase operations
Database operatIons

3 DATABASE OPERATIONS
3
The following describes a program, called DbOperations consisting of several test methods.
The
The methods should show how to perform the most basic database operations using JDBC,
where I only care about operations that maintains the database tables and hence SQL
INSERT, UPDATE and DELETE statements, as well as operations that extract data from
tables and thus SQL SELECT.

3.1 SQL STATEMENTS


3.1
The following test method uses the table history, and starts to delete a row in the table,
The
insert a row, execute a query, update a row and finally execute a query again. This means
that the method performs all the above four database operations. The code is as follows:

private static void test01()


{
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234"))
{
Statement stmt = conn.createStatement();
System.out.println(stmt.executeUpdate(

In the past four years we have drilled

81,000 km
That’s more than twice around the world.

Who are we?


We are the world’s leading oilfield services company. Working
globally—often in remote and challenging locations—we invent,
design, engineer, manufacture, apply, and maintain technology
to help customers find and produce oil and gas safely.

Who are we looking for?


We offer countless opportunities in the following domains:
n Engineering, Research, and Operations
n Geoscience and Petrotechnical
n Commercial and Business

If you are a self-motivated graduate looking for a dynamic career,


apply to join our team. What will you be?

careers.slb.com

15
15
JAVA 6: JDBC AND DATABASE APPLICATIONS Database operations
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS dataBase operatIons
dataBase operatIons

"DELETE FROM
"DELETE FROM history
history WHERE
WHERE name
name LIKE
LIKE 'Ragnar
'Ragnar Lodbrog'"));
Lodbrog'"));
System.out.println(stmt.executeUpdate(
System.out.println(stmt.executeUpdate(
"INSERT INTO
"INSERT INTO history
history (name)
(name) VALUES('Ragnar
VALUES('Ragnar Lodbrog')"));
Lodbrog')"));
ResultSet res
ResultSet res == stmt.executeQuery("SELECT
stmt.executeQuery("SELECT name,
name, title,
title, birth,
birth, death,
death, country
country
FROM history
FROM history WHERE
WHERE name
name LIKE
LIKE 'Ragnar
'Ragnar Lodbrog'");
Lodbrog'");
while(res.next())
while(res.next())
System.out.printf("%-25s%-10s%5d%5d %s\n",
System.out.printf("%-25s%-10s%5d%5d %s\n", res.getString("name"),
res.getString("name"),
res.getString("title"), res.getInt("birth"),
res.getString("title"), res.getInt("birth"), res.getInt("death"),
res.getInt("death"),
res.getString("country"));
res.getString("country"));
System.out.println(stmt.executeUpdate("UPDATE history
System.out.println(stmt.executeUpdate("UPDATE history SET
SET title
title == 'Viking',
'Viking',
country == 'DK'
country 'DK' WHERE
WHERE name
name LIKE
LIKE 'Ragnar
'Ragnar Lodbrog'"));
Lodbrog'"));
res == stmt.executeQuery("SELECT
res stmt.executeQuery("SELECT name,
name, title,
title, birth,
birth, death,
death, country
country FROM
FROM history
history
WHERE name
WHERE name LIKE
LIKE 'Ragnar
'Ragnar Lodbrog'");
Lodbrog'");
while(res.next()) System.out.printf("%-25s%-10s%5d%5d
while(res.next()) System.out.printf("%-25s%-10s%5d%5d %s\n",
%s\n",
res.getString("name"), res.getString("title"),
res.getString("name"), res.getString("title"), res.getInt("birth"),
res.getInt("birth"),
res.getInt("death"), res.getString("country"));
res.getInt("death"), res.getString("country"));
}}
catch (SQLException
catch (SQLException ex)
ex)
{{
System.out.println(ex);
System.out.println(ex);
}}
}}

IfIf the
the method
method isis performed,
performed, you
you get
get the
the result:
result:

00
11
Ragnar Lodbrog
Ragnar Lodbrog NULL
NULL 00 00 null
null
11
Ragnar Lodbrog
Ragnar Lodbrog VIKING
VIKING 00 00 DK
DK

In the
In
In the same
the same manner
same manner as
manner asas in in the
in the program
the program HelloJDBC
program HelloJDBC the
HelloJDBC the first
the first thing
first thing is
thing isis toto open
to open aaa connection
open connection
connection
to the
to
to the database,
the database, and
database, and it
and itit is
isis done
done in
done in exactly
in exactly the
exactly the same
the same way,
same way, but
way, but with
but with the
with the difference,
the difference, that
difference, that the
that the
the
Connection object
Connection
Connection object this
object this time
this time is
time isis created
created within
created within the
within the parenteses
the parenteses in
parenteses in the
in the try
the try statement.
try statement. This
statement. This means
This means
means
that the
that
that the connection
the connection is
connection isis automatically
automatically closed
automatically closed when
closed when the
when the method
the method exits
method exits the
exits the try
the try block,
try block, and
block, and in
and in
in
the same
the
the same manner
same manner as
manner as in
as in closing
in closing files
closing files it
files itit provides
provides aaa more
provides more simple
more simple and
simple and also
and also more
also more readable
more readable code.
readable code.
code.
ItIt should
It should be
should be noted
be noted that
noted that when
that when aaa database
when database connection
database connection is
connection isis closed,
closed, it
closed, itit also
also closes
also closes any
closes any opening
any opening
opening
statements that
statements
statements that may
that may be
may be associated
be associated with
associated with the
with the object.
the object.
object.

16
16
16
JAVA 6: JDBC AND DATABASE APPLICATIONS Database operations
JAVA 6: JDBC AND DATABASE APPLICATIONS dataBase operatIons

The
The trytry block
block starts
starts to
to create
create aa Statement
Statement object, and the
object, and the next
next statement
statement performs
performs aa SQL
SQL
DELETE.
DELETE. It It isis executed
executed with
with the
the method
method executeUpdate() which, in
executeUpdate() which, in addition
addition to
to DELETE
DELETE
isis used
used toto perform
perform INSERT
INSERT and and UPDATE
UPDATE statements. The method
statements. The method returns
returns the
the number
number
of
of rows
rows that
that have
have changed.
changed. In In this
this case,
case, the
the statement delete the
statement delete the rows
rows inin which
which the
the name’s
name’s
value
value isis Ragnar
Ragnar Lodbrog.
Lodbrog. IfIf this
this is
is the
the first
first time
time that the method
that the method is is run,
run, there
there may
may not
not be
be
such
such aa row,
row, and
and the the method
method willwill return
return 0. 0. If
If the method has
the method has been
been completed,
completed, there
there are
are aa
row
row with
with that
that value
value in
in the
the column
column name,
name, andand the method will
the method will return
return 11 and
and then
then will
will print
print
11 onon the
the screen
screen corresponding
corresponding to to the
the above
above result.
result.

The
The next
next statement
statement performs
performs aa SQL
SQL INSERT
INSERT andand inserts thus aa row
inserts thus row in
in the
the table.
table. You
You should
should
note
note that
that the
the statement
statement only
only add
add aa value
value in
in the
the column name, which
column name, which is
is okay
okay because
because the
the
other
other columns
columns allow
allow null
null values.
values. When
When this
this statement
statement is is executed,
executed, the
the method
method also
also prints
prints
11 on
on the
the screen,
screen, because
because there
there are
are inserted
inserted one
one row in the
row in the table.
table.

The
The next
next statement
statement againagain performs
performs aa SQL
SQL SELECT,
SELECT, andand this
this time
time it’s
it’s with
with executeQuery(),
executeQuery(),
which
which justjust isis used
used to to execute
execute aa SELECT.
SELECT. TheThe query extract the
query extract the rows
rows where
where thethe column
column
name
name has has the
the value
value Ragnar
Ragnar Lodbrog.
Lodbrog. There
There is
is only one such
only one such row,
row, and
and the
the row
row isis printed
printed inin
the
the next
next statement.
statement. The The result
result is
is as
as shown
shown in
in the third line
the third line above.
above. Note
Note that
that the
the method
method
loops
loops over
over the
the objects
objects inin the
the ResultSet
ResultSet object
object using
using aa while
while loop.
loop. It
It is
is obviously
obviously no no need
need
for
for aa loop
loop when
when II know
know that
that there
there is
is only
only one
one row, but it
row, but it is
is necessary
necessary to to perform
perform res.next()
res.next()
to
to step
step toto the
the first
first row.
row.

Finally
Finally isis performed
performed aa SQL
SQL UPDATE and again with the method executeUpdate(),
executeUpdate(), and
and as
as
the
the last
last isis performed
performed aa new
new query, showing that the row has been updated.
updated.

PREPAREDSTATEMENTS
PREPAREDSTATEMENTS
In
In the
the above
above examples,
examples, allall database operations are executed with a Statement
Statement object,
object, which
which
isis an
an object
object that
that represents
represents a static SQL statement, and thus an SQL statement
statement that
that can
can not
not
be
be changed.
changed. There
There isis also
also a class called PreparedStatement, which represents
represents aa parameterized
parameterized
SQL
SQL statement.
statement. The
The objective
objective of the following test method is to show how, aa SQL
SQL expression
expression
can
can useuse parameters.
parameters.

The
The project
project DbOperations
DbOperations have a class called Person that represents a row in
in the
the table
table history.
history.
This means
This means that
that class
class contains
contains a variable for each column in the table:

public class Person implements Comparable<Person>, Serializable


{
private int id; // number, that is a surrogate key in the database
private String name; // the person's name
private String title; // the person's title

17
17
JAVA 6: JDBC AND DATABASE APPLICATIONS Database operations
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS dataBase
dataBaseoperatIons
operatIons

private
privateInteger
Integerbirth;
birth; ////birth,
birth,start
starttotoreign
reignororother
other
private
privateInteger
Integerdeath;
death; ////year
yearofofdeath
death
private
privateString
Stringcountry;
country; ////country
countrycode
codeasastwo
twocharacters
characters
private
privateString
Stringdescription;
description; ////a adescription
descriptionofofthe
theperson
person

I IIwill
willnot
will notshow
not showthe
show thefull
the fullclass
full classhere,
class here,partly
here, partlybecause
partly becauseI IIearlier
because earlierhave
earlier haveseen
have seenon
seen onan
on analmost
an almostidentical
almost identical
identical
class,
class,and
class, andpartly
and partlybecause
partly becausethe
because theclass
the classconsisting
class consistingprimarily
consisting primarilyofof
primarily ofget
getand
get andset
and setmethods.
set methods.Note,
methods. Note,however,
Note, however,
however,
that
thatthe
that thetype
the typeofof
type ofbirth
birthand
birth anddeath
and deathisisisInteger
death Integernot
Integer notint.
not int.The
int. Thereason
The reasonisisisthat
reason thatthe
that thetwo
the twocolumns
two columnsinin
columns in
thethedatabase
the databasecould
database couldcontain
could containnull
contain null(and
null (andan
(and anint
an intcan
int cannot
can notbe
not benull
be null).).
null ).

The
Theclass
The classDbOperations
class DbOperationshas
DbOperations hasthe
has thefollowing
the followingmethod
following methodthat
method thatcreates
that createsan
creates anArrayList
an ArrayListwith
ArrayList withsome
with somePerson
some Person
Person
objects
objects(I(I
objects (Ihave
haveonly
have onlyshown
only shownthe
shown thefirst
the firstperson
first person–––there
person thereare
there are12):
are 12):
12):

private
privatestatic
staticList<Person>
List<Person>createPersons()
createPersons()
{{
List<Person>
List<Person>list
list= =new
newArrayList();
ArrayList();
list.add(new
list.add(newPerson(
Person(
"Chlochilaicus",
"Chlochilaicus","Legends
"Legendsking",
king",null,
null,null,
null,"DK",
"DK","Ruled
"Ruledabout
about515"));
515"));
...
...
return
returnlist;
list;
}}

Linköping University
– Innovative, well ranked, European
Interested in Engineering and its various
branches? Kick-start your career with an
English-taught master’s degree.

liu.se/master

Click here!

18
18 18
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS dataBase operations
Database operatIons

Then the
Then the test
test method:
method:

private static void test02()


{
List<Person> list = createPersons();
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234"))
{
PreparedStatement stmt =
conn.prepareStatement("DELETE FROM history WHERE name LIKE ?");
for (Person pers : list)
{
stmt.setString(1, pers.getName());
stmt.executeUpdate();
}
stmt = conn.prepareStatement("INSERT INTO history
(name, title, birth, death, country, description) VALUES (?, ?, ?, ?, ?, ?)");
for (Person pers : list)
{
stmt.setString(1, pers.getName());
stmt.setString(2, pers.getTitle());
if (pers.getBirth() == null) stmt.setNull(3, java.sql.Types.INTEGER);
else stmt.setInt(3, pers.getBirth());
if (pers.getDeath() == null) stmt.setNull(4, java.sql.Types.INTEGER);
else stmt.setInt(4, pers.getDeath());
stmt.setString(5, pers.getCountry());
stmt.setString(6, pers.getDescription());
stmt.executeUpdate();
}
}
catch (SQLException ex)
{
System.out.println(ex);
}
print("SELECT * FROM history WHERE title LIKE 'Legends king'");
}

First the
First the method
method creates
creates aa list
list with
with the
the 12
12 Person
Person objects.
objects. Then, Then, opening
opening aa connection
connection
to the
to the database,
database, and
and for
for this
this connection
connection isis created
created aa PreparedStatement
PreparedStatement object.
object. The
The class
class
PreparedStatement isis derived
PreparedStatement derived fromfrom Statement
Statement and
and represents
represents as as such
such aa SQL
SQL expression,
expression, but
but
an expression
an expression that
that maymay have
have parameters.
parameters. InIn this
this case
case itit isis aa SQL
SQL DELETE,
DELETE, and and there
there isis aa
single parameter
single parameter that
that isis indicated
indicated with
with aa question
question mark.
mark. The The next
next loop
loop must
must delete
delete all
all the
the
people in
people in the
the list
list (if
(if available),
available), and and for
for each
each iteration
iteration thethe looploop performs
performs aa DELETE,
DELETE, but but
first itit must
first must insert
insert aa value
value for for the
the column
column name
name in in the
the SQL SQL expression.
expression. That
That is,
is, that
that the
the
question mark
question mark must
must be be replaced
replaced by by aa value:
value:

stmt.setString(1, pers.getNavn());

19
19
JAVA
JAVA6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Database
dataBaseoperations
operatIons

Here,
Here,11indicates
indicatesititisisthe
thefirst
firstparameter
parameter(and
(andthere
thereisisjust
justthe
thesame),
same),while
whilethethelast
lastparameter
parameter
isis the
the value.
value. The
The value
value isis assigned
assigned the
the stmt
stmt object
object with
with setString()
setString() asas the
the type
type of
of the
the column
column
isis VARCHAR.
VARCHAR. There There are are similar
similar methods
methods for
for other
other column
column types.
types.

When
When thethe loop
loop isis completed,
completed, another
another PreparedStatement
PreparedStatement isis created,
created, but
but this
this time
time for
for aa SQL
SQL
INSERT.
INSERT. ItIt has
has nono fewer
fewer than than six
six parameters,
parameters, and and itit isis used
used to
to insert
insert aa row
row inin the
the table
table for
for
each
each person
person inin the
the list.
list. ItIt happens
happens in in aa loop,
loop, and
and for
for eacheach repetition,
repetition, thethe 66 parameters
parameters are are
initialized.
initialized. You
You should
should especially
especially note
note howhow to
to specify
specify that that aa value
value must
must be be null.
null.

Finally
Finally the
the test
test method
method perfoms
perfoms thethe method
method print()
print() with
with aa SQL
SQL SELECT
SELECT asas parameter,
parameter,
which
which isis aa method
method that
that prints
prints the
the rows
rows extracted.
extracted.

EXERCISE
EXERCISE 22
You
You should
should use
use MySQL
MySQLWorkbench
Workbench to to add
add aa new
new table
table to
to the
the database
database padata.
padata. You
You should
should
do
do this
this by
by writing
writing aa script
script (the
(the same
same wayway asas shown
shown forfor the
the table
table history)
history) when
when the
the table
table
should
should bebe named
named currency,
currency, and
and itit should
should have
have three
three columns:
columns:

1. code,
1. code, which
which mustmust bebe aa currency
currency code
code ofof three
three characters,
characters, which
which must
must be
be the
the
primary
primary key
key
2.
2. name,
name, that
that must
must bebe the
the name
name ofof the
the currency
currency and
and can
can be
be up
up to
to 30
30 characters
characters
3.
3. rate,
rate, which
which must
must be
be the
the exchange
exchange rate
rate and
and having
having the
the type
type DECIMAL
DECIMAL with with room
room
for
for 10
10 digits
digits and
and 44 after
after the
the decimal
decimal point
point

You
You must
must then
then write
write aa program
program using
using the
the following
following array
array to
to update
update the
the currency
currency table.
table. The
The
program
program should
should start
start by
by deleting
deleting the
the entire
entire contents
contents of
of the
the table
table (with
(with aa simple
simple DELETE),
DELETE),
and
and then
then itit must
must use
use aa PreparedStatment
PreparedStatment andand insert
insert aa row
row for
for each
each string
string inin the
the array:
array:

private static String[] kurser =


{
"Danske kroner;DKK;100.00",
"Euro;EUR;746.00",
"Amerikanske dollar;USD;674.44",
"Britiske pund;GBP;1034.10",
"Svenske kroner;SEK;79.31",
"Norske kroner;NOK;79.68",
"Schweiziske franc;CHF;685.66",
"Japanske yen;JPY;5.6065",
"Australske dollar;AUD;487.61",
"Brasilianske real;BRL;171.98",
"Bulgarske lev;BGN;381.43",
"Canadiske dollar;CAD;510.19",
"Filippinske peso;PHP;14.40",
"Hongkong dollar;HKD;87.02",
"Indiske rupee;INR;10.38",

20
20
JAVA 6: JDBC AND DATABASE APPLICATIONS Database operations
JAVA 6: JDBC AND DATABASE APPLICATIONS dataBase operatIons

"Indonesiske rupiah;IDR;0.0494",
"Israelske shekel;ILS;174.48",
"Kinesiske Yuan renminbi;CNY;106.17",
"Kroatiske kuna;HRK;97.87",
"Malaysiske ringgit;MYR;157.78",
"Mexicanske peso;MXN;40.65",
"New Zealandske dollar;NZD;458.77",
"Polske zloty;PLN;173.82",
"Rumænske lei;RON;168.13",
"Russiske rubel;RUB;10.42",
"Singapore dollar;SGD;483.72",
"Sydafrikanske rand;ZAR;49.08",
"Sydkoreanske won;KRW;0.5933",
"Thailandske baht;THB;19.00",
"Tjekkiske koruna;CZK;27.53",
"Tyrkiske lira;TRY;231.78",
"Ungarske forint;HUF;2.385"
};

To insert a value for


for the
the rate
rate in
in aa PreparedStatement,
PreparedStatement, you
youmust
mustspecify
specifythat
thatthe
thetype
typeis is
DECIMAL, and herehere you
you can
can use
use setBigDecimal().
setBigDecimal().

Before you run the


the program,
program, you
you may
may update
updatethe
thearray
arraywith
withtoday’s
today’scurrent
currentrates.
rates.


678'<)25<2850$67(5©6'(*5((

&KDOPHUV8QLYHUVLW\RI7HFKQRORJ\FRQGXFWVUHVHDUFKDQGHGXFDWLRQLQHQJLQHHU
LQJDQGQDWXUDOVFLHQFHVDUFKLWHFWXUHWHFKQRORJ\UHODWHGPDWKHPDWLFDOVFLHQFHV
DQGQDXWLFDOVFLHQFHV%HKLQGDOOWKDW&KDOPHUVDFFRPSOLVKHVWKHDLPSHUVLVWV
IRUFRQWULEXWLQJWRDVXVWDLQDEOHIXWXUH¤ERWKQDWLRQDOO\DQGJOREDOO\
9LVLWXVRQ&KDOPHUVVHRU1H[W6WRS&KDOPHUVRQIDFHERRN

21
21
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS ResultSet
resultset

4 RESULTSET
4 RESULTSET
The
The most
most complex
complex SQLSQL statement
statement isis SELECT,
SELECT, and and itit isis aa very
very complex
complex statement
statement with
with many
many
options.
options. From
From aa Java
Java program
program youyou can
can perform
perform aa SQL
SQL SELECT SELECT with with executeQuery(),
executeQuery(), and and
although
although thethe SELECT
SELECT statement
statement can
can bebe complex,
complex, the the result
result seen
seen from
from thethe Java
Java program
program isis
always
always the
the same:
same: AA ResultSet
ResultSet object.
object. You
You can
can think
think of of the the object
object as
as aa collection
collection ofof objects
objects
with
with an
an internal
internal cursor
cursor that
that points
points toto aa current
current object
object (a (a row),
row), or
or the
the cursor
cursor isis null
null ifif itit isis
not
not pointing
pointing to to anything.
anything. TheThe class
class ResultSet
ResultSet defines
defines many many methods
methods thatthat can
can basically
basically be be
divided
divided into
into three
three kinds:
kinds:

1.
1. methods
methods toto move
move the
the cursor
cursor
2.
2. get
get methods
methods that
that returns
returns the
the value
value for
for aa column
column at at the
the current
current row
row
3.
3. update
update methods
methods that
that update
update the
the column
column value
value for
for the
the current
current row
row and
and you
you even
even
have
have the
the opportunity
opportunity toto write
write the
the changes
changes back
back to
to the
the database
database

To
To create
create aa Statement
Statement object,
object, II have
have so
so far
far used
used the
the following
following syntax:
syntax:

Statement stmt = connection.createStatement();

that
that creates
creates aa Statement
Statement object,
object, but
but createStatement()
createStatement() has
has an
an override
override of
of the
the form:
form:

createStatement(int resultSetType, int resultSetConcurrency)

Here you
Here you can
can for
for the
the first
first parameter
parameter set
set three
three values:
values:

1. ResultSet.TYPE_FORWARD_ONLY,
1. ResultSet.TYPE_FORWARD_ONLY, that that means,
means, that
that the
the cursor
cursor can
can move
move forward
forward
and isis the
and the default
default value
value
2. ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.TYPE_SCROLL_INSENSITIVE, that that means,
means, thatthat the
the cursor
cursor kan
kan move
move
both back
both back and
and forth,
forth, and
and that
that the
the ResultSet
ResultSet isis not
not updated
updated withwith changes
changes that
that other
other
users had
users had to
to make
make to to the
the database
database after
after this
this ResulSet
ResulSet isis created
created
3. ResultSet.TYPE_SCROLL_SENSITIVE,
3. ResultSet.TYPE_SCROLL_SENSITIVE, which which means
means the the same
same asas above,
above, but
but with
with
the difference
the difference that
that the
the resultset
resultset isis updated
updated withwith changes
changes thatthat other
other users
users had
had to
to
make to
make to the
the database
database after
after this
this ResulSet
ResulSet isis created
created

As default
As default aa ResulSet
ResulSet isis readonly,
readonly, but
but for
for the
the last
last of
of above
above two
two parameters
parameters there
there are
are two
two options
options

1. ResultSet.CONCUR_READ_ONLY,
1. ResultSet.CONCUR_READ_ONLY,that
thatcreates
createsaareadonly
readonlyResultSet
ResultSetand
andisisthe
thedefault
default
2. ResultSet.CONCUR_UPDATABLE,
2. ResultSet.CONCUR_UPDATABLE, which
which creates
creates aa ResultSet,
ResultSet, that
that isis updatable
updatable

22
22
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS ResultSet
resultset

You can set the same parameters for prepareStatement() with the following syntax:

prepareStatement(String sql, int resultSetType, int resultSetConcurrency)

A ResulSet has many ways to navigate the cursor, and you are encouraged to examine
the options. They are basically self-explanatory, and the following test method (which is a
method in DbOperations) gives examples of the use of the methods on a ResultSet, where
you can scroll back and forth:

private static void test03()


{
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234"))
{
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet res = stmt.executeQuery("SELECT name, birth, death FROM history
where title LIKE 'King' OR title LIKE 'Queen'");
res.last();
print(res);
res.first();
print(res);
res.next();
print(res);
res.previous();
print(res);
res.absolute(50);
print(res);
res.relative(-5);
print(res);
res.afterLast();
while (res.previous()) if (res.getString(1).startsWith("Gorm")) break;
print(res);
System.out.println(res.getRow());
res.last();
System.out.println(res.getRow() + 1);
}
catch (SQLException ex)
{
System.out.println(ex);
}
}

23
23
JAVA 6: JDBC AND DATABASE APPLICATIONS resultset
JAVA
JAVA6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS ResultSet
resultset

If you performs the method, you get the result:


IfIf you
you performs
performs the
the method,
method, you
you get
get the
the result:
result:
Margrethe d. 2. 1972 0
Margrethe d. 2.
Gorm den Gamle 1972
0 0
958
Gorm den Gamle
Harald Blåtand 0
958 958
987
Harald Blåtand
Gorm den Gamle 958
0 987
958
Gorm den Gamle
Frederik d. 9. 0
1947 958
1972
Frederik d. 9.
Christian d. 8. 1947
1839 1972
1848
Christian d. 8.
Gorm den Gamle 1839
0 1848
958
Gorm
1 den Gamle 0 958
1
52
52

Each line
Each line are
are printed
printed with
with the
the method
method
Each line are printed with the method
private static void print(ResultSet res)
private
{ static void print(ResultSet res)
{ try
try
{
{ String name = res.getString(1);
String name
int birth = = res.getString(1);
res.getInt(2);
int death
int birth =
= res.getInt(3);
res.getInt(2);
int death = res.getInt(3);
System.out.printf("%-20s%5d%5d\n", name, birth, death);
} System.out.printf("%-20s%5d%5d\n", name, birth, death);
}

Welcome to
our world
of teaching!
Innovation, flat hierarchies
and open-minded professors

Study in Sweden -
close collaboration
with future employers
Mälardalen university collaborates with
many employers such as ABB, volvo and
Ericsson

TAKE THE
debajyoti nag
Sweden, and particularly
MDH, has a very impres-
sive reputation in the field

RIGHT TRACK
of Embedded Systems Re-
search, and the course
design is very close to the
industry requirements.
He’ll tell you all about it and
answer your questions at
mdustudent.com
give your career a headstart at mälardalen university
www.mdh.se

24
24
24
JAVA 6: JDBC AND DATABASE APPLICATIONS ResultSet
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS resultset
resultset

catch
catch (Exception
(Exception ex)
ex)
{{
System.out.println(ex);
System.out.println(ex);
}}
}}

AA resultset
resultset has has aa number
number of of methods
methods usedused toto retrieve
retrieve the
the values
values for
for the
the current
current row,
row, and
and
in
in the
the foregoing
foregoing examples,
examples, II each
each time
time has
has referenced
referenced thethe values
values with
with thethe column
column name.
name.
Actually,
Actually, itit isis also
also allowed
allowed toto enter
enter an
an index,
index, starting
starting with
with 11 for
for the
the first
first column.
column. YouYou should
should
note
note that
that the
the index
index does
does not
not refer
refer toto the
the physical
physical table,
table, but
but the
the columns
columns specified
specified inin the
the
SELECT
SELECT statement.
statement. In In this
this case,
case, there
there are
are three
three columns,
columns, andand thethe indexes
indexes are
are therefore
therefore 1,1,
22 and
and 3.3.

4.1
4.1 UPDATE
4.1 UPDATE A
A RESULTSET
RESULTSET
The
The following
The following test
test method
method shows
shows that
that one
one can
can update
update aa resultset:
resultset:

private
private static
static void
void test04()
test04()
{{
try
try (Connection
(Connection conn
conn == DriverManager.getConnection(
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false",
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "pa", "Volmer_1234"))
"Volmer_1234"))
{{
Statement
Statement stmt
stmt == conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet.CONCUR_UPDATABLE);
ResultSet
ResultSet resres == stmt.executeQuery("SELECT
stmt.executeQuery("SELECT ** FROM FROM history");
history");
insert(res);
insert(res);
res.last();
res.last();
printRow(res);
printRow(res);
update(res,
update(res, "King",
"King", "Probably
"Probably lived
lived between
between the
the years
years 400
400 and
and 500");
500");
printRow(res);
printRow(res);
update(res,
update(res, "Legends
"Legends king",
king", res.getString("description")
res.getString("description") ++
"" and
and his
his story
story isis described
described in
in Rolf
Rolf Krake's
Krake's Saga");
Saga");
printRow(res);
printRow(res);
while
while (true)
(true)
{{
res
res == stmt.executeQuery("SELECT
stmt.executeQuery("SELECT id id FROM
FROM history
history WHERE
WHERE name
name LIKE
LIKE 'Rolf%'");
'Rolf%'");
if
if (res.next())
(res.next())
{{
int
int id;
id;
System.out.println(id
System.out.println(id == res.getInt("id"));
res.getInt("id"));
print("SELECT
print("SELECT ** FROM
FROM history
history WHERE
WHERE id
id == "" ++ id);
id);
delete(res);
delete(res);
}} else
else break;
break;
}}
}}

25
25
25
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS ResultSet
resultset
JAVA 6: JDBC AND DATABASE APPLICATIONS resultset

catch
catch (SQLException
(SQLException ex)
ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

First,
First, you
First,you notice
younotice that
noticethat
thatthethe creation
thecreation of
ofaaaStatement
creationof Statement object
Statementobject that
objectthat allows
thatallows you
allowsyou to
youto update
updateaaaResultSet.
toupdate ResultSet.
ResultSet.
Next,
Next,
Next, allall rows
all rows are
rows are extracted
are extracted from
extracted from the
from the table
the table history,
table history, and
history, and then
and then the
then the method
the method insert()
insert() isis
method insert() called
is called
called
with
with the
with the ResultSet
the ResultSet as a parameter:
ResultSet asas aa parameter:
parameter:

private
private static
static void
void insert(ResultSet
insert(ResultSet res)
res)
{
{
try
try
{
{
res.moveToInsertRow();
res.moveToInsertRow();
res.updateString("name", "Rolf Krake");
res.updateString("name", "Rolf Krake");
res.updateString("country", "DK");
res.updateString("country", "DK");
res.insertRow();
res.insertRow();
}
}
catch (SQLException ex)
catch (SQLException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

This
This method adds a new row to the ResultSet object and assigns values to two of the columns.
This method
method adds
adds aa new
new row
row to
to the
the ResultSet
ResultSet object
object and
and assigns
assigns values
values to
to two
two of
of the
the columns.
columns.
The
The last method writes the changes physically back to the database. IfIfyou do not want that,
The last method writes the changes physically back to the database. If you do not want that,
last method writes the changes physically back to the database. you do not want that,
you
you can
can omit
omitthis
thisstatement,
statement, and
and the
the row
rowisisjust
justinserted
inserted in
inthe
theResultSet
ResultSet object
objectin
inmemonry.
memonry.
you can omit this statement, and the row is just inserted in the ResultSet object in memonry.

After
After the new row isisinserted, the test method set the cursor to the last row and the prints
After the
the new
new row
row is inserted,
inserted, the
the test
test method
method set
set the
the cursor
cursor to
to the
the last
last row
row and
and the
the prints
prints
the
therow
row by
byaamethod
method printRow().
printRow(). The
The next
nextstatement
statement calls
callsaamethod
method update(),
update(),which
whichupdates
updates
the row by a method printRow(). The next statement calls a method update(), which updates
the
the row that the cursor points to:
the row
row that
that the
the cursor
cursor points
points to:
to:

private
private static
static void
void update(ResultSet
update(ResultSet res,
res, String
String title,
title, String description)
String description)
{
{
try
try
{
{
res.updateString("title", title);
res.updateString("title", title);
res.updateString("description",
res.updateString("description", description);
description);
res.updateRow();
res.updateRow();
}
}
catch (SQLException ex)
catch (SQLException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

26
26
26
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE APPLICATIONS ResultSet
resultset

There
There isis updated two columns, and again it’s the last statement,
statement, which
which writes
writes the
the changes
changes
back
back toto the database. The test method prints then the
the row
row again,
again, so
so you
you can
can see
see that
that the
the
changes
changes are made, after which the row is updated once
once again.
again.

Next,
Next, thethe method performs an infinite while loop where
where itit starts
starts to
to execute
execute aa query
query on on
persons
persons where the name starts with Rolf. There should onlyonly bebe 1.
1. If
If there
there isis such
such aa row
row (res.
(res.
next() is
next() is true) the row is removed with the method delete().
delete(). If
If the
the row
row isis not
not found
found aa break
break
isis performed,
performed, and the loop stops. The goals is to show
show that
that the
the updates
updates are are physically
physically in in
the database,
the database, so that in the next iteration, no rows are found.
found. TheThe method
method delete()
delete() isis quite
quite
simple and deletes the row that the cursor points to:
simple

private static void delete(ResultSet res)


{
try
{
res.deleteRow();
}
catch (SQLException ex)
{
System.out.println(ex);
}
}

LIFE SCIENCE IN UMEÅ, SWEDEN


– YOUR CHOICE!
• 32 000 students • world class research • top class teachers
• modern campus • ranked nr 1 in Sweden by international students
• study in English

– Bachelor’s programme in Life Science


– Master’s programme in Chemistry
– Master’s programme in Molecular Biology

Download
brochure
here!

27
27
JAVA
JAVA 6: JDBC AND DATABASE APPLICATIONS ResultSet
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS resultset
resultset

You
You should
You should note
should note that
note that the
that the test
the test method’s
test method’s while
method’s while loop
while loop in
loop in case
in case there
case there are
there are found
are found aaa row
found row calls
row calls the
calls the
the
method print()
method print()
method with
print() with a SQL
with aa SQL expression
SQL expression
expression asas a parameter.
as aa parameter.
parameter. TheThe objective
The objective is
objective is to
is to show
to show that
show that the
that the
the
new
new row
new row is
row is available
is available
available onon request
on request associated
request associated with
associated with another
with another connection,
another connection, and
connection, and thus
and thus the
thus the row
row isis
the row is
physically
physically stored
stored in
in the
the database.
database. If
If you
you performs
performs the
the test
test method,
method, the
the
physically stored in the database. If you performs the test method, the result could be: result
result could
could be:
be:

Rolf
Rolf Krake
Krake null
null 0
0 0
0 DK
DK
null
null

Rolf
Rolf Krake
Krake King
King 0
0 0
0 DK
DK
Probably lived
Probably lived between the years
between the years 400
400 and
and 500
500

Rolf
Rolf Krake
Krake Legends
Legends king
king 0
0 0
0 DK
DK
Probably lived between the years 400
Probably lived between the years 400 andand 500 and his
500 and his
story
story is
is described
described in
in Rolf
Rolf Krake's
Krake's Saga
Saga

70
70
Rolf Krake
Rolf Krake Legends king
Legends king 0
0 0 DK
0 DK
Probably lived between the years 400 and 500
Probably lived between the years 400 and 500 andand his
his
story
story is
is described
described in
in Rolf
Rolf Krake's
Krake's Saga
Saga

The
The test
The test method
test method
method also also uses
uses aaa method
also uses method printRow(),
method printRow(), which
printRow(), which prints
prints aaa row
which prints row on
row on the
on the screen
the screen (the
screen (the row
(the row
row
that
that the
the cursor
cursor points
points to).
to). The
The method
method requires
requires no
no special
special explanation
explanation
that the cursor points to). The method requires no special explanation and is not shown and
and is
is not
not shown
shown
here,
here, but
but itit
here, but it isis has
has aaa statement
is has statement that
that isis
statement that commented
is commented
commented out:out:
out:

//
// System.out.println(res.rowInserted()
System.out.println(res.rowInserted() +
+ "
" "
" +
+ res.rowUpdated()
res.rowUpdated() +
+ "
" "
" +
+
res.rowDeleted());
res.rowDeleted());

When
When itit
When it isis commented
is commented
commented out, out,
out, itit
it isis simply
is simply because
because itit
simply because does
it does not
does not work.
not work. The
work. The method
The method
method shouldshould test
should test
test
whether a ResultSet
whether aa ResultSet
whether has
ResultSet has a row
has aa row
row thatthat is inserted,
that isis inserted, updated,
inserted, updated,
updated, or or deleted,
or deleted, and
deleted, and where
and where
where the the changes
the changes
changes
are not
are
are not yet
not yet written
yet written back
written back to
back to the
to the database.
the database. Note
database. Note specifically
Note specifically that
specifically that when
that when aaa row
when row isis
row is deleted,
deleted, there
deleted, there
there
isis nothing
is nothing else,
nothing else, than
else, than
than thethe row
row isis
the row marked
is marked
marked as as deleted
as deleted
deleted in in the
in the resultset,
the resultset, but
but itit
resultset, but it isis not
is not removed.
not removed.
removed.
These methods
These methods
These methods are are described
are described
described in in the
in the JDBC
the JDBC standard,
JDBC standard,
standard, butbut it is not
but itit isis not the
not the same
the same
same as as the
as the supplier
the supplier
supplier ofof
of
the JDBC
the JDBC
the JDBC driverdriver implements
driver implements
implements these these methods
these methods
methods and and it does
and itit does not
does not apply
not apply
apply toto the
to the JDBC
the JDBC driver
JDBC driver for
driver for
for
MySQL. The
MySQL.
MySQL. The lesson
The lesson isis
lesson is that
that whether
that whether the
whether the characteristics
the characteristics of
characteristics of the
of the JDBC
the JDBC standard
JDBC standard isis
standard is implemented,
implemented,
implemented,
depends
depends on
depends on
on the the specific
the specific driver,
specific driver,
driver, andand thus
and thus of
thus of the
of the database
the database product
database product
product used,used, but
used, but also
but also the
also the version
the version
version
of the
of the
of driver.
the driver.
driver.

28
28
28
JAVA6:
JAVA 6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS resultset
ResultSet

4.2 MUNICIPALITIES
4.2 MUNICIPALITIES AND
AND ZIPCODES
ZIPCODES
Following the
Following the above,
above, II will
will show
show aa more
more realistic
realistic example
example of
of aa database
database application.
application. The
The
database isis still
database still padata,
padata, but
but II will
will expands
expands itit with
with four
four new
new tables.
tables. The
The first
first should
should be
be aa
table of
table of Danish
Danish regions:
regions:

regnr
regnr name
name

1081
1081 RegionNordjylland
Region Nordjylland

1082
1082 RegionMidtjylland
Region Midtjylland

1083
1083 RegionSyddanmark
Region Syddanmark

1084
1084 RegionHovedstaden
Region Hovedstaden

1085
1085 RegionSjælland
Region Sjælland

and isis thus


and thus aa simple
simple table
table with
with two
two columns
columns and
and five
five rows.
rows. The
The next
next table
table isis aa table
table of
of
Danish municipalities,
Danish municipalities, where
where each
each municipality
municipality isis recorded
recorded as
as

1. the
1. the municipality
municipality number
number (a(a unique
unique number
number of
of 33 digits)
digits)
2. the
2. the municipality
municipality name
name
3. the
3. the region,
region, that
that the
the municipalty
municipalty belongs
belongs to
to
4. the
4. the municipality’s
municipality’s area
area in
in square
square kilometers
kilometers
5. the
5. the municipality’s
municipality’s inhabitants
inhabitants
6. year
6. year of
of the
the municipality’s
municipality’s inhabitants
inhabitants

The region
The region isis the
the region
region number,
number, soso there
there isis aa 1:n
1:n relation
relation between
between municipalities
municipalities and
and
regions, such
regions, such that
that each
each municipality
municipality isis linked
linked toto aa specific
specific region.
region.

The third
The third table
table isis aa table
table of
of Danish
Danish zip
zip codes
codes and
and isis aa simple
simple table
table with
with two
two columns
columns that
that
contain respectively
contain respectively the the code
code and
and the
the city
city name.
name.

AA municipality
municipality uses
uses several
several zip
zip codes,
codes, and
and aa specific
specific zip
zip code
code can
can actually
actually be
be used
used by
by several
several
municipalities,and
municipalities, andsuch
suchthere
thereisisananm:n
m:nrelation
relationbetween
betweenmunicipalities
municipalitiesand
andzipzipcodes.
codes.Such
Suchaa
relationshipisisimplemented
relationship implementedwith withaatable
tablewhere
whereaarowrowconnects
connectsaazip
zipcode
codeand
andaamunicipality.
municipality.

Accordingly, you
Accordingly, you can
can expand
expand the
the database
database with
with four
four new
new tables
tables using
using the
the following
following script:
script:

use padata;
drop table if exists post;
drop table if exists municipality;
drop table if exists region;
drop table if exists zipcode;

29
29
JAVA 6: JDBC AND DATABASE APPLICATIONS ResultSet
JAVA 6: JDBC AND DATABASE APPLICATIONS resultset

create table region


(
regnr int not null primary key,
name varchar(30) not null
);

create table municipality


(
munnr int not null primary key,
name varchar(30) not null,
regnr int not null,
area decimal(10, 2),
number int,
year int,
foreign key (regnr) references region(regnr)
);

create table zipcode


(
code char(4) not null primary key,
city varchar(30) not null
);

Scholarships

Open your mind to


new opportunities
With 31,000 students, Linnaeus University is
one of the larger universities in Sweden. We
are a modern university, known for our strong
international profile. Every year more than Bachelor programmes in
1,600 international students from all over the Business & Economics | Computer Science/IT |
world choose to enjoy the friendly atmosphere Design | Mathematics
and active student life at Linnaeus University.
Master programmes in
Welcome to join us! Business & Economics | Behavioural Sciences | Computer
Science/IT | Cultural Studies & Social Sciences | Design |
Mathematics | Natural Sciences | Technology & Engineering
Summer Academy courses

30
30
JAVA 6: JDBC AND DATABASE APPLICATIONS ResultSet
JAVA 6: JDBC AND DATABASE APPLICATIONS resultset
JAVA 6: JDBC AND DATABASE APPLICATIONS resultset

create table post


create table post
(
(
code char(4) not null,
code char(4) not null,
munnr int not null,
munnr int not null,
primary key (code, munnr),
primary key (code, munnr),
foreign key (code) references zipcode(code),
foreign key (code) references zipcode(code),
foreign key (munnr) references municipality(munnr)
foreign key (munnr) references municipality(munnr)
);
);

insert into region values (1081, 'Region Nordjylland');


insert into region values (1081, 'Region Nordjylland');
insert into region values (1082, 'Region Midtjylland');
insert into region values (1082, 'Region Midtjylland');
insert into region values (1083, 'Region Syddanmark');
insert into region values (1083, 'Region Syddanmark');
insert into region values (1084, 'Region Hovedstaden');
insert into region values (1084, 'Region Hovedstaden');
insert into region values (1085, 'Region Sjælland');
insert into region values (1085, 'Region Sjælland');

There is not much to explain, but you should note that the script inserts the five rows in
There
There isis not
not much
much toto explain,
explain, butbut you
you should
should note
note that
that the
the script
script inserts
inserts the
the five
five rows
rows in
in
the table region. The script is called CreateDenmark.sql.
the
the table
table region.
region. The
The script
script isis called
called CreateDenmark.sql.
CreateDenmark.sql.

It you performs the script, it creates the four tables, but the tables other than region are all
ItIt you
you performs
performs the the script,
script, itit creates
creates the
the four
four tables,
tables, but
but the
the tables
tables other
other than
than region
region are are all
all
empty and contains no data. The books directory contains a file named zipcodes. It is a text
empty
empty and and contains
contains no no data.
data. TheThe books
books directory
directory contains
contains aa file
file named
named zipcodes.
zipcodes. ItIt isis aa text
text
file that contains 1106 lines with Danish zip codes, where each line contains a code and
file
file that
that contains
contains 1106 1106 lines
lines with
with Danish
Danish zipzip codes,
codes, where
where each
each line
line contains
contains aa code
code and and
a city name separated by a semicolon. The file should be used to update the table zipcode,
aa city
city name
name separated
separated by by aa semicolon.
semicolon. The The file
file should
should be
be used
used to to update
update the
the table
table zipcode,
zipcode,
and you can do that with a SQL command LOAD DATA INFILE. It is a command that
and
and youyou can
can dodo that
that with
with aa SQLSQL command
command LOAD LOAD DATADATA INFILE.
INFILE. ItIt isis aa command
command that that
MySQL do not like, because it is not without risk, and you can, in principle, copy anything
MySQL
MySQL do do not
not like,
like, because
because itit isis not
not without
without risk,
risk, and
and you
you can,
can, in in principle,
principle, copy
copy anything
anything
into the database. Therefore, you can not immediately execute the command from MySQL
into
into the
the database.
database. Therefore,
Therefore, you you cancan not
not immediately
immediately execute
execute thethe command
command from from MySQLMySQL
Workbench. To use the command to load the content of the file to a database, you has to
Workbench.
Workbench. To To use
use the
the command
command to to load
load the
the content
content ofof the
the file
file to
to aa database,
database, you
you has has toto
place the file in a special directory that only root has access to:
place
place thethe file
file in
in aa special
special directory
directory that that only
only root
root has
has access
access to:
to:
/var/lib/mysql-files
/var/lib/mysql-files

I have (as root) in this directory created a subdirectory data. Next, I have copied the
II have
have (as
(as root)
root) in
in this
this directory
directory created
created aa subdirectory
subdirectory data.
data. Next,
Next, II have
have copied
copied the
the
file zipcodes to this directory. Then the table can be updated using the following script
file
file zipcodes
zipcodes to
to this
this directory.
directory. Then
Then the
the table
table can
can be
be updated
updated using
using the
the following
following script
script
(LoadZipcodes.sql ):
(LoadZipcodes.sql ):
(LoadZipcodes.sql ):
use padata;
use padata;
load data infile '/var/lib/mysql-files/data/zipcodes' into table zipcode
load data infile '/var/lib/mysql-files/data/zipcodes' into table zipcode
CHARACTER SET UTF8
CHARACTER SET UTF8
fields terminated by ';' lines terminated by '\n'
fields terminated by ';' lines terminated by '\n'
(code, city);
(code, city);

The result
The result is that the
the table zipcode
zipcode now have
have 1106 rows.
rows.
The result isis that
that the table
table zipcode now
now have 1106
1106 rows.

31
31
31
JAVA
JAVA 6:
JAVA 6: JDBC
6: JDBC AND
JDBC AND DATABASE
AND DATABASE APPLICATIONS
DATABASE APPLICATIONS
APPLICATIONS ResultSet
resultset
resultset

Then
Then there
there isis the
the table
table municipality,
municipality, and
and the
the book’s
book’s directory
directory hashas aa file
file municipalities
municipalities that
that
contains
contains lines
lines with
with data
data on
on Danish
Danish municipalities.
municipalities. Below
Below isis shown
shown thethe first
first three
three lines:
lines:

773;Morsø Kommune;1081;364.42;20815;2015;7900;7950;7960;7970;7980;7990
787;Thisted Kommune;1081;1095.63;44078;2015;7700;7730;7741;7742;7752;
7755;7760;7770
810;Brønderslev Kommune;1081;633.38;35781;2015;9320;9330;9340;9352;9370;
9382;9440;9480;9700;9740;9750;9760

AA line
line contains
contains separated
separated by
by semicolons
semicolons

1.
1. municipality
municipality number
number
2.
2. municipality
municipality name
name
3.
3. region
region number
number
4.
4. area
area
5.
5. number of
number of inhabitants
inhabitants
6.
6. year
year for
for number
number ofof inhabitants
inhabitants

This
This isis followed
followed byby aa variable
variable number
number of of zip
zip codes,
codes, which
which are
are the
the zip
zip codes
codes that
that this
this
municipality uses. For each line in the file there must be inserted
municipality uses. For each line in the file there must be inserted a row in the tablea row in the table
municipality,
municipality, andand for
for each
each zipzip code
code aa row
row in
in the
the table
table post.
post. The
The easiest
easiest isis to
to write
write aa small
small
program
program thatthat reads
reads the
the file
file and
and updates
updates the
the database:
database:

package createmunicipalities;

import java.sql.*;
import java.io.*;
import java.math.*;

public class CreateMunicipalities


{
public static void main(String[] args)
{
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234");
BufferedReader reader = new BufferedReader(
new FileReader(System.getProperty("user.home") + "/data/municipalities")))
{
Statement stmt = conn.createStatement();
stmt.execute("DELETE FROM post");
stmt.execute("DELETE FROM municipality");
PreparedStatement stmt1 = conn.prepareStatement(
"INSERT INTO municipality VALUES(?, ?, ?, ?, ?, ?)");
PreparedStatement stmt2 = conn.prepareStatement(
"INSERT INTO post VALUES(?, ?)");

32
32
32
JAVA 6: JDBC AND DATABASE APPLICATIONS ResultSet
JAVA 6: JDBC AND DATABASE APPLICATIONS resultset

for (String line = reader.readLine(); line != null; line = reader.readLine())


{
String[] elem = line.split(";");
int munnr = Integer.parseInt(elem[0]);
stmt1.setInt(1, munnr);
stmt1.setString(2, elem[1]);
stmt1.setInt(3, Integer.parseInt(elem[2]));
stmt1.setBigDecimal(4, new BigDecimal(elem[3]));
stmt1.setInt(5, Integer.parseInt(elem[4]));
stmt1.setInt(6, Integer.parseInt(elem[5]));
stmt1.executeUpdate();
System.out.println(elem[1]);
for (int i = 6; i < elem.length; ++i)
{
try
{
stmt2.setString(1, zipcode(elem[i]));
stmt2.setInt(2, munnr);
stmt2.executeUpdate();
}
catch (Exception ex)
{
System.out.println(munnr + " " + elem[i]);
}

YOUR WORK AT TOMTOM WILL


BE TOUCHED BY MILLIONS.
AROUND THE WORLD. EVERYDAY.
Join us now on www.TomTom.jobs
follow us on

#ACHIEVEMORE

33

33
JAVA 6: JDBC AND DATABASE APPLICATIONS ResultSet
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS resultset
resultset

}}
}}
}}
catch
catch (Exception
(Exception ex)
ex)
{{
System.out.println(ex);
System.out.println(ex);
}}
}}

private
private static
static String
String zipcode(String
zipcode(String str)
str)
{{
if
if (str.length()
(str.length() ==
== 3)
3) str
str == "0"
"0" ++ str;
str;
return
return str;
str;
}}
}}

In
In the
In the
the parentheses
parentheses
parentheses after after
after try
try
try are
are
are in
in
in the
the
the usual
usual
usual wayway
way opened
opened
opened aaa connection
connection
connection to to
to the
the
the database
database
database and and
and
the
the file
the file
file municipalities
municipalities
municipalities that that
that III have
have
have copied
copied
copied to to
to the
the
the folder
folder
folder data
data
data under
under
under mymy
my home
home
home directory.
directory.
directory. TheThe
The
first
first thing
first thing
thing that that
that happens
happens
happens is isis that
that
that the
the
the content
content
content of of
of the
the
the two
two
two database
database
database tables
tables
tables are
are
are deleted
deleted
deleted andand
and then
then
then
are
are created
are created
created two two
two PreparedStatement
PreparedStatement
PreparedStatement objects objects
objects with
with
with INSERT
INSERT
INSERT statements
statements
statements for for
for the
the
the two
two
two tables.
tables.
tables. The
The
The
next
next for
next for
for loop
loop
loop reads
reads
reads the
the
the file
file
file line
line
line by
by
by line,
line,
line, and
and
and each
each
each line
line
line is
isis split
split
split into
into
into tokens
tokens
tokens that
that
that are
are
are used
used
used toto
to
initialize
initialize the
initialize the
the parameters
parameters
parameters of of
of stmt1.
stmt1.
stmt1. After
After
After having
having
having inserted
inserted
inserted aaa rowrow
row inin
in the
the
the table
table
table municipalities,
municipalities,
municipalities,
there
there is
there isis inner
inner
inner forfor
for loop
loop
loop that
that
that runs
runs
runs over
over
over all
all
all zip
zip
zip codes
codes
codes and and
and insert
insert
insert rows
rows
rows inin
in the
the
the table
table
table post
post
post for
for
for this
this
this
municipality.
municipality.
municipality.

You
YouYou should
should
should note
note
note that
that
that ititit actually
actually
actually takes
takes
takes aaa long
long
long time
time
time to
to
to execute
execute
execute the the
the program.
program.
program. TheThe
The program
program
program
executes
executes more
executes more
more than
than
than 2000
2000
2000 SQL SQL
SQL INSERT
INSERT
INSERT commands,
commands,
commands, andand
and ititit is
isis aaa tedious
tedious
tedious procces
procces
procces to
to
to make
make
make
ititit from
from
from Java,
Java,
Java, as
as
as shown
shown
shown in in
in this
this
this example,
example,
example, and and
and there
there
there are
are
are also
also
also as as
as shown
shown
shown later
later
later better
better
better ways
ways
ways to
to
to
accomplish
accomplish the
accomplish the
the same.
same.
same.

As
As an
As an
an example
example
example of
of
of aaa program
program
program that
that
that uses
uses
uses the
the
the new
new
new tables,
tables,
tables, determines
determines
determines the
the
the following
following
following test
test
test method
method
method
(still
(stillaaamethod
(still method
methodin
in
inthe
the
theprogram
program
programDbOperations)
DbOperations)
DbOperations)thethe
thenumber
number
numberof of
ofresidents
residents
residentsin
in
inRegion
Region
RegionMidtjylland:
Midtjylland:
Midtjylland:

private
private static
static void
void test05()
test05()
{{
try
try (Connection
(Connection conn
conn == DriverManager.getConnection(
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false",
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa","pa", "Volmer_1234"))
"Volmer_1234"))
{{
Statement
Statement stmt
stmt == conn.createStatement();
conn.createStatement();
ResultSet
ResultSet res
res == stmt.executeQuery("SELECT
stmt.executeQuery("SELECT number
number FROM
FROM municipality
municipality AS
AS M,
M,
region
region AS
AS RR WHERE
WHERE M.regnr
M.regnr == R.regnr
R.regnr AND
AND R.name
R.name LIKE
LIKE '%Midtjylland'");
'%Midtjylland'");
int
int count
count == 0;
0;
while
while (res.next())
(res.next()) count
count +=
+= res.getInt("number");
res.getInt("number");

34
34
34
JAVA 6: JDBC AND DATABASE APPLICATIONS ResultSet
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS resultset
resultset

System.out.println("Number
System.out.println("Number of
of inhabitants
inhabitants in
in Region
Region Midtjylland:
Midtjylland: "
" +
+ count);
count);
}
}
catch
catch (SQLException
(SQLException ex)
ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

You should note that the only thing new is a little more complex SQL SELECT statement,
but from Java there is nothing new.

EXERCISE 3
Write a program that from the numbers in the table municipality on the screen prints the
population density in Jutland and Fyn.

PROBLEM 1
You must expand the database padata with two other tables. The first should be named
world and must contains the names of all continents:

create
create table
table world
world
(
(
code
code char(2)
char(2) not
not null
null primary
primary key,
key,
name varchar(15)
name varchar(15) not
not null
null
);
);

The
The table
table must
must contain
contain the
the following
following data:
data:

--- AS Asia
AS
AS Asia
Asia
--- AF Africa
AF Africa
AF Africa
--- NA
NA North
NA North America
America
--- SA
SA South
SA South America
America
--- AN Antarctica
AN Antarctica
AN Antarctica
--- EU Europe
EU Europe
EU Europe
--- OC Oceania
OC Oceania
OC Oceania

The
The second
second table
table should
should contain
contain information
information on
on countries:
countries:

create
create table
table country
country
(
(
code2
code2 char(2)
char(2) not
not null
null primary
primary key,
key, #
# country
country code
code
code3
code3 varchar(3),
varchar(3), #
# country code
country code
name
name varchar(50)
varchar(50) not
not null,
null, #
# the country's name
the country's name

35
35
35
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS ResultSet
resultset
JAVA 6: JDBC AND DATABASE APPLICATIONS resultset

area int, # the country's area


area int, # the country's area
number int, # number of inhabitants
number int, # number of inhabitants
continent char(2), # continent
continent char(2), # continent
currency char(3), # currency code
currency char(3), # currency code
foreign key (continent) references world(code),
foreign key (continent) references world(code),
foreign key (currency) references currency(code)
foreign key (currency) references currency(code)
);
);

Write
Writeaascript
scriptthat
thatcreates
createsthese
thesetwo
twotables
tablesand
andinserts
insertsinformation
informationabout
aboutthe
thecontinents
continentsin
in
Write a script that creates these two tables and inserts information about the continents in
the
the first
first table.
table.
the first table.

The
The folder
folder to
to this
this book
book contains
contains aa file
file called
called countries.
countries. ItIt isis aa plain
plain text
text file
file in
in which
which each
each
The folder to this book contains a file called countries. It is a plain text file in which each
line
line contains
contains information
information about
about aa country.
country. Below
Below isis the
the first
first lines:
lines:
line contains information about a country. Below is the first lines:

AF;AFG;Afghanistan
AF;AFG;Afghanistan
AL;ALB;Albanien
AL;ALB;Albanien
DZ;DZA;Algir
DZ;DZA;Algir
AS;ASM;Amerikansk Samoa
AS;ASM;Amerikansk Samoa
US;USA;Amerikas Forenede Stater (USA);US Dollar;USD;553.14
US;USA;Amerikas Forenede Stater (USA);US Dollar;USD;553.14
AD;AND;Andorra
AD;AND;Andorra
AO;AGO;Angola
AO;AGO;Angola
AI;AIA;Anguilla
AI;AIA;Anguilla

36
36
36
JAVA 6: JDBC AND DATABASE APPLICATIONS ResultSet
JAVA 6: JDBC AND DATABASE APPLICATIONS resultset
JAVA 6: JDBC AND DATABASE APPLICATIONS resultset

AQ;ATA;Antarktis
AQ;ATA;Antarktis
AG;ATG;Antigua og
AG;ATG;Antigua og Barbuda
Barbuda
AR;ARG;Argentina
AR;ARG;Argentina
AM;ARM;Armenien
AM;ARM;Armenien
AW;ABW;Aruba
AW;ABW;Aruba
AZ;AZE;Aserbajdsjan
AZ;AZE;Aserbajdsjan
AU;AUS;Australien;Australsk dollar;AUD;568.80
AU;AUS;Australien;Australsk dollar;AUD;568.80
BS;BHS;Bahama
BS;BHS;Bahama
BH;BHR;Bahrain
BH;BHR;Bahrain

The
Thefields
The fieldsare
fields areseparated
are separatedby
separated bysemicolons.
by semicolons.For
semicolons. Foreach
For eachcountry
each countrythere
country thereisisisatat
there atleast
least333fields:
least fields:country
fields: country
country
code
codeon
code on222characters
on characters(primary
characters (primarykey),
(primary key),country
key), countrycode
country codeon
code on333characters
on characters(which
characters (whichmay
(which maybe
may beblank)
be blank)
blank)
and
andthe
and thecountry’s
the country’sname.
country’s name.In
name. Inaddition,
In addition,there
addition, theremay
there maybe
may bethree
be threeadditional
three additionalfields,
additional fields,that
fields, thatisisisthe
that thename
the name
name
of
ofthe
of thecurrency
the currencywhich
currency whichthe
which thecountry
the countryuses,
country uses,the
uses, thecurrency
the currencycode
currency codeand
code andan
and ananexchange
exchangerate.
exchange rate.
rate.

You
Youmust
You mustnow
must nowwrite
now writeaaaprogram
write programthat
program thatcan
that canupdate
can updatethe
update thetable
the tablecountry
table countryby
country byreading
by readingthe
reading theabove
the abovefile.
above file.
file.
IfIfIfthere
thereisisisaaacurrency,
there currency,the
currency, thecurrency
the currencycode
currency codeisisisinserted
code insertedin
inserted inthe
in thecolumn
the columnfor
column forcurrency,
for currency,otherwise
currency, otherwise
otherwise
the
thevalue
the valueshould
value shouldjust
should justbe
just benull.
be null.There
null. Thereisisisaaaparticular
There particularproblem
particular problemwhen
problem whenthe
when thefile
the filefor
file foraaacountry
for country
country
indicates
indicatesaaacurrency,
indicates currency,and
currency, andthat
and thatcurrency
that currencynot
currency notexitst
not exitstin
exitst inthe
in thetable
the tablecurrency.
table currency.For
currency. Forthese
For thesecurrencies,
these currencies,
currencies,
the
theprogram
the programmust
program mustalso
must alsoupdate
also updatethe
update thetable
the tablecurrency.
table currency.
currency.

4.3
4.3 STORED
4.3 STOREDPROCEDURES
STORED PROCEDURES
PROCEDURES
AAAstoredstoredprocedure
stored procedureisisisaaascript
procedure scriptthat
script thatcontains
that containsSQL
contains SQLstatements
SQL statementsthat
statements thatisisisexecuted
that executedwhen
executed whenthe
when the
the
procedure
procedureisisisperformed.
procedure performed.When
performed. Whenone
When onespeaks
one speaksof
speaks ofaaastored
of storedprocedure,
stored procedure,itititmeans
procedure, meansthat
means thatthe
that theprocedure
the procedure
procedure
isisistranslated
translatedand
translated andstored
and storedin
stored inthe
in thedatabase,
the database,which
database, whichmeans
which meansthat
means thatitititisisishighly
that highlyeffective
highly effectiveto
effective toexecute
to executeaaa
execute
stored
storedprocedure.
stored procedure.In
procedure. InMySQL
In MySQLWorkbench
MySQL Workbenchyou
Workbench youcan
you cancreate
can createaaastored
create storedprocedure
stored procedureby
procedure byright-clicking
by right-clicking
right-clicking
Stored
StoredProcedures
Stored Proceduresfor
Procedures forthe
for thedatabase
the databaseunder
database underSchemas,
under Schemas,and
Schemas, andyou
and youget
you getasas
get asaaaskeleton
skeletonfor
skeleton foraaaprocedure:
for procedure:
procedure:

CREATE PROCEDURE
CREATE PROCEDURE 'new_procedure'
'new_procedure' ()
()
BEGIN
BEGIN

END
END

Asan
As
As anexample,
an example,IIIhave
example, havewritten
have writtenaaavery
written verysimple
very simpleprocedure
simple procedurewhich
procedure whichOUT
which OUTparameter
OUT parameterreturns
parameter returnsthe
returns the
the
numberof
number
number ofpersons
of personsin
persons inthe
in thetable
the tablehistory
table historywhere
history wherethe
where theyear
the yearfalls
year fallswithin
falls withinaaarange:
within range:
range:

CREATE PROCEDURE
CREATE PROCEDURE 'persons'
'persons' (IN
(IN aa int,
int, IN
IN bb int, OUT
int, OUT cc int)
int)
BEGIN
BEGIN
SELECT count(id)
SELECT count(id) FROM
FROM history
history WHERE
WHERE (a
(a <=
<= birth AND
birth AND birth
birth <=
<= b)
b) OR
OR
(a <= death AND death <= b) INTO
(a <= death AND death <= b) INTO c; c;
END
END

37
37
37
JAVA
JAVA
JAVA6:6:
6:JDBC
JDBC
JDBCAND
AND
ANDDATABASE
DATABASE
DATABASEAPPLICATIONS
APPLICATIONS
APPLICATIONS ResultSet
resultset
resultset

When
When you you have
have written
written the
the procedure,
procedure, you
you must
must click
click Apply,
Apply, and
and you
you are
are then
then given
given aa
window
window asas shown
shown on
on the
the next
next page,
page, and
and click
click Apply
Apply again
again the
the procedure
procedure isis translated
translated and
and
store
storeititin
inthe
thedatabase.
database.Once
Oncethetheprocedure
procedureisissaved,
saved,ititcan
canbebeexecuted
executedlike
likelike
likeany
anyother
other
SQL
SQL command:
command:

use
use padata;
padata;

call padata.persons(1100,
call padata.persons(1100, 1600,
1600, @count);
@count);
select @count;
select @count;

The following
The following test
test method
method shows
shows how
how to
to execute
execute aa stored
stored procedure
procedure from
from aa Java
Java program:
program:

private static
private static void
void test06()
test06()
{
{
try (Connection
try (Connection conn
conn =
= DriverManager.getConnection(
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false",
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa",
"pa", "Volmer_1234"))
"Volmer_1234"))
{
{
CallableStatement
CallableStatement stmt
stmt == conn.prepareCall("CALL
conn.prepareCall("CALL persons(?,
persons(?, ?,
?, ?)");
?)");
stmt.setInt(1, 1200);
stmt.setInt(1, 1200);
stmt.setInt(2,
stmt.setInt(2, 1300);
1300);
stmt.registerOutParameter(3, Types.INTEGER);
stmt.registerOutParameter(3, Types.INTEGER);
stmt.execute();
stmt.execute();
System.out.println(stmt.getInt(3));
System.out.println(stmt.getInt(3));
}
}
catch (SQLException
catch (SQLException ex)
ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

JDBC defines
JDBC defines inin form
form of of the
the types
types Statement
Statement and
and PreparedStatement
PreparedStatement typestypes that
that represents
represents
aa SQL
SQL statement,
statement, and and there
there isis also
also aa type
type called
called CallableStatement,
CallableStatement, representing
representing aa stored
stored
procedure. ItIt isis parameterized
procedure. parameterized in in the
the same
same way
way asas aa PreparedStatement,
PreparedStatement, and and the
the input
input
parameters are
parameters are initialized
initialized inin the
the same
same manner.
manner. By By contrast,
contrast, the
the output
output parameters
parameters mustmust
be registered
be registered with
with aa special
special syntax
syntax including
including to to assign
assign aa type.
type. After
After this,
this, the
the procedure
procedure isis
executed with
executed with the
the method
method execute().
execute().

38
38
38
JAVA 6: JDBC AND DATABASE APPLICATIONS ResultSet

39
JAVA 6: JDBC AND DATABASE APPLICATIONS Data types

5 DATA TYPES
In a database table, each column has a data type and in Java data is stored in variables of
a particular type. It is therefore necessary to know how JDBC are converting types in the
database to the Java variables, and vice versa. The preceding programs have already shown
many examples, for example when values are retrieved from a ResultSet with a get method,
or when parameters in a PreparedStatement are initialized with a set method. The following
table shows the relationship between these types:

SQL Java Methods

VARCHAR String getString(), setString()

CHAR String getString(), setString()

LONGVARCHAR String getString(), setString()

BIT boolean getBoolean(), setBoolean()

NUMERIC java.math.BigDecimal getBigDecimal(), setBigDecimal()

TINYINT byte getByte(), setByte()

SMALLINT short getShort(), setShort()

INTEGER int getInt(), setInt()

BIGINT long getLong(), setLong()

REAL float getFloat(), setFloat()

FLOAT float getFloat(), setFloat()

DOUBLE double getDouble(), setDouble()

VARBINARY byte[] getBytes(), setBytes()

BINARY byte[] getBytes(), setBytes()

DATE java.sql.Date getDate(), setDate()

TIME java.sql.Time getTime(), setTime()

TIMESTAMP java.sql.Timestamp getTimestamp(), setTimestamp()

CLOB java.sql.Clob getClob(), setClob()

BLOB java.sql.Blob getBlob(), setBlob()

40
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Data
datatypes
types

SQL
SQL Java
Java Methods
Methods

ARRAY
ARRAY java.sql.Array
java.sql.Array getArray(),
getArray(),setArray()
setArray()

REF
REF java.sql.Ref
java.sql.Ref getRef(),
getRef(),setRef()
setRef()

STRUCT
STRUCT java.sql.Struct
java.sql.Struct getStruct(),
getStruct(),setStruct()
setStruct()

Thus,
Thus,ititisisimportant
importanttotonote
notethat
thatthe
thepackage
packagejava.sql
java.sqldefines
definesspecial
specialdata
datatypes
typesthat
thatcorrespond
correspond
totosome
someofofthe theSQL
SQLdatadatatypes.
types.Converting
Convertingbetween
betweentypes
typestotodate
dateand
andtime
timeoften
oftenresults
results
ininproblems
problemswith withdatabase
databaseapplications,
applications,and
andtotofacilitate
facilitatethe
theproblem
problemofofconverting
convertingthese
these
types,
types,I Ihave
haveexpanded
expandedmy mylibrary
libraryPaLib
PaLibwith
withthe
thefollowing
followingclass:
class:

package palib.util;

import java.util.*;

public class Db
{
public static java.sql.Date toDate(Date date)
{
return new java.sql.Date(date.getTime());
}

public static java.sql.Time toTime(Date date)


{
return new java.sql.Time(date.getTime());
}

public static java.sql.Timestamp toTimestamp(Date date)


{
return new java.sql.Timestamp(date.getTime());
}

public static java.sql.Date toDate(Calendar date)


{
return new java.sql.Date(date.getTimeInMillis());
}

public static java.sql.Time toTime(Calendar date)


{
return new java.sql.Time(date.getTimeInMillis());
}

4141
JAVA 6: JDBC AND DATABASE APPLICATIONS Data types
JAVA 6: JDBC AND DATABASE APPLICATIONS data types

public static java.sql.Timestamp toTimestamp(Calendar date)


{
return new java.sql.Timestamp(date.getTimeInMillis());
}

public static Calendar toCalendar(java.sql.Date date)


{
Calendar c = new GregorianCalendar();
c.setTime(date);
return c;
}

public static Calendar toCalendar(java.sql.Time time)


{
Calendar c = new GregorianCalendar();
c.setTime(time);
return c;
}

WE WILL TURN YOUR CV


INTO AN OPPORTUNITY
OF A LIFETIME

Do you like cars? Would you like to be a part of a successful brand?


Send us your CV on
As a constructer at ŠKODA AUTO you will put great things in motion. Things that will
www.employerforlife.com
ease everyday lives of people all around Send us your CV. We will give it an entirely
new new dimension.

42
42
JAVA 6: JDBC AND DATABASE APPLICATIONS data types
JAVA 6: JDBC AND DATABASE APPLICATIONS Data types

public static Calendar toCalendar(java.sql.Date date, java.sql.Time time)


{
Calendar c1 = new GregorianCalendar();
Calendar c2 = new GregorianCalendar();
c1.setTime(date);
c2.setTime(time);
c1.set(Calendar.HOUR_OF_DAY, c2.get(Calendar.HOUR_OF_DAY));
c1.set(Calendar.MINUTE, c2.get(Calendar.MINUTE));
c1.set(Calendar.SECOND, c2.get(Calendar.SECOND));
return c1;
}

/**
* Converts a string to a Calendar object. The string should be of the form
* DD-MM-YYYY HH:MM:SS
* and must represent a valid date and time. The year must be at least
* 1700, as the date must be from the Gregorian calendar.
* It is permitted only to indicate the date and not a time indication.
* @param str The string to be converted
* @return The string is converted into a Calendar object
* @throws UtilException If the string does not represent a valid date
*/ public static Calendar toCalendar(String str) throws UtilException
{
try
{
int day = Integer.parseInt(str.substring(0, 2));
int month = Integer.parseInt(str.substring(3, 5));
int year = Integer.parseInt(str.substring(6, 10));
int hour = 0;
int minute = 0;
int second = 0;
if (str.length() > 10)
{
hour = Integer.parseInt(str.substring(11, 13));
minute = Integer.parseInt(str.substring(14, 16));
second = Integer.parseInt(str.substring(17).trim());
}
if (year >= 1700 && month >= 1 && month <= 12 && day >= 1 &&
day <= days(year, month) && hour >= 0 && hour <= 23 && minute >= 0 &&
minute <= 59 && second >= 0 && second <= 59)
return new GregorianCalendar(year, month – 1, day, hour, minute, second);
}

43
43
JAVA 6: JDBC AND DATABASE APPLICATIONS Data types
JAVA 6: JDBC AND DATABASE APPLICATIONS data types

catch (Exception ex)


{
}
throw new UtilException("String can not be converted to a Calendar object");
}

public static String toStr(Calendar cal)


{
return String.format("%02d-%02d-%04d %02d:%02d:%02d",
cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1,
cal.get(Calendar.YEAR), cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
}

public static boolean leapYear(int aar)


{
return aar % 100 == 0 ? aar % 400 == 0 : aar % 4 == 0;
}

private static int days(int aar, int mdr)


{
if (mdr == 2) return leapYear(aar) ? 29 : 28;
if (mdr == 4 || mdr == 6 || mdr == 9 || mdr == 11) return 30;
return 31;
}
}

It should be easy enough to figure out each method, and from practical programming, it is
especially important to be able to convert to and from Calendar objects and the corresponding
SQL data types. The following test method uses the above conversion methods:

private static void test07()


{
System.out.println(Db.toDate(new java.util.Date()));
System.out.println(Db.toTime(new java.util.Date()));
System.out.println(Db.toDate(Calendar.getInstance()));
System.out.println(Db.toTime(Calendar.getInstance()));
System.out.println(Db.toStr(Db.toCalendar(Db.toDate(new java.util.Date()))));
System.out.println(Db.toStr(Db.toCalendar(Db.toTime(new java.util.Date()))));
System.out.println(Db.toStr(Db.toCalendar(Db.toDate(new java.util.Date()),
Db.toTime(new java.util.Date()))));
}

44
44
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Data
datatypes
types

and
andan
anexample
exampleofofrunning
runningthe
themethod
methodcould
couldbe:
be:

2017-01-01
16:41:08
2017-01-01
16:41:08
01-01-2017 16:41:08
01-01-2017 16:41:08
01-01-2017 16:41:08

Another problem concerning data type is NULL values as null in databases and Java is not
Another problem concerning data type is NULL values as null in databases and Java is not
the same. For example will a ResultSet’s get methods convert a NULL value for a primitive
the same. For example will a ResultSet’s get methods convert a NULL value for a primitive
type to the default value (often 0), which is not always appropriate. In the test method
type to the default value (often 0), which is not always appropriate. In the test method
test02(), I have shown how you from an application can write NULL values to the database.
test02(), I have shown how you from an application can write NULL values to the database.
The following test method demonstrates an application of the method wasNull() where a
The following test method demonstrates an application of the method wasNull() where a
ResultSet tests whether the last value, that is returned with a get method, was NULL:
ResultSet tests whether the last value, that is returned with a get method, was NULL:

Develop the tools we need for Life Science


Masters Degree in Bioinformatics

Bioinformatics is the
exciting field where biology,
computer science, and
mathematics meet.

We solve problems from


biology and medicine using
methods and tools from
computer science and
mathematics.

Read more about this and our other international masters degree programmes at www.uu.se/master

45
45
JAVA 6: JDBC AND DATABASE APPLICATIONS Data types
JAVA 6: JDBC AND DATABASE APPLICATIONS data types
JAVA 6: JDBC AND DATABASE APPLICATIONS data types

private
private static
static void
void test08()
test08()
{{
try
try (Connection
(Connection conn conn == DriverManager.getConnection(
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false",
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "pa", "Volmer_1234"))
"Volmer_1234"))
{{
Statement
Statement stmtstmt == conn.createStatement();
conn.createStatement();
ResultSet
ResultSet res = stmt.executeQuery("SELECT name,
res = stmt.executeQuery("SELECT name, birth,
birth, death
death FROM
FROM history
history
WHERE
WHERE title
title Like
Like 'Queen'");
'Queen'");
while
while (res.next())
(res.next())
{{
String
String navn
navn == res.getString(1);
res.getString(1);
String
String birth
birth == "";
"";
int t = res.getInt(2);
int t = res.getInt(2);
if
if (!res.wasNull())
(!res.wasNull()) birthbirth == ""
"" ++ t;
t;
String death = "";
String death = "";
tt == res.getInt(3);
res.getInt(3);
if
if (!res.wasNull()) death
(!res.wasNull()) death == ""
"" ++ t;
t;
System.out.printf("%-25s%4s
System.out.printf("%-25s%4s –– %4s\n",
%4s\n", navn,
navn, birth,
birth, death);
death);
}}
}}
catch
catch (SQLException
(SQLException ex) ex)
{{
System.out.println(ex);
System.out.println(ex);
}}
}}

IfIf the
If the method
method isis
the method performed,
is performed, you
performed, you get
you get the
get the result:
the result:
result:

Margrete
Margrete d.
d. 1. 1387 –– 1412
1. 1387 1412
Margrethe d. 2. 1972 ––
Margrethe d. 2. 1972

46
46
46
JAVA 6: JDBC AND DATABASE APPLICATIONS transaCtIons
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Transactions
transaCtIons

6 TRANSACTIONS
6 TRANSACTIONS
When performing
When performing anan SQL
SQL statement
statement using
using either
either aa Statement
Statement oror PreparedStatement
PreparedStatement object,
object,
the database
the database is
is immediately
immediately updated.
updated. Sometimes
Sometimes it it is
is not
not appropriate,
appropriate, since
since you
you often
often have
have
multiple SQL
multiple SQL statements
statements thart
thart must
must be
be executed
executed asas aa whole,
whole, where
where either
either all
all statements
statements are
are
executed correctly
executed correctly or
or everyone
everyone are
are ignored.
ignored. InIn database
database contexts
contexts wee
wee talks
talks about
about aa transaction
transaction
that simply
that simply means
means that
that multiple
multiple SQL
SQL statements
statements can
can be be perceived
perceived as
as aa whole.
whole. The
The following
following
test method
test method inserts
inserts three
three rows
rows in
in the
the table
table history,
history, where
where thethe three
three statements
statements is is performed
performed
as aa transaction:
as transaction:

private
private static
static void
void test09()
test09()
{
{
Connection
Connection conn
conn == null;
null;
try
try
{
{
conn
conn == DriverManager.getConnection(
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false",
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "pa", "Volmer_1234");
"Volmer_1234");
conn.setAutoCommit(false);
conn.setAutoCommit(false);
ArrayList<Integer>
ArrayList<Integer> list
list == new
new ArrayList();
ArrayList();
PreparedStatement stmt = conn.prepareStatement(
PreparedStatement stmt = conn.prepareStatement(
"INSERT
"INSERT INTO
INTO history
history (name,
(name, title)
title) VALUES
VALUES (?,
(?, ?)");
?)");
insert(stmt, "Egil Skallegrimson", null,
insert(stmt, "Egil Skallegrimson", null, list);list);
insert(stmt,
insert(stmt, "Knud
"Knud Larvard",
Larvard", "Duke",
"Duke", list);
list);
insert(stmt, null, "Rebel", list);
insert(stmt, null, "Rebel", list);
conn.commit();
conn.commit();
}
}
catch(SQLException
catch(SQLException ex)ex)
{
{
if
if (conn
(conn !=
!= null)
null) try
try {{ conn.rollback();
conn.rollback(); } } catch
catch (Exception
(Exception ex2)
ex2) {}
{}
System.out.println(ex);
System.out.println(ex);
}
}
finally
finally
{
{
try
try {{ if
if (conn
(conn !=
!= null)
null) conn.close();
conn.close(); }} catch
catch (SQLException
(SQLException ex)
ex) {}
{}
}
}
}
}

First
First as
as before
before is
is in
in the
the usual
usual way
way created
created aa connection
connection to
to the
the database,
database, and
and the
the next
next statement
statement
says
says that there should be no auto commit. This means that subsequent SQL statements are
that there should be no auto commit. This means that subsequent SQL statements are
not immediately been performed on the database (they are marked as statements
not immediately been performed on the database (they are marked as statements that can that can
be
be rolled
rolled back),
back), and
and the
the effect
effect will
will not
not appear
appear before
before performing
performing aa commit().
commit(). The
The statement
statement

conn.setAutoCommit(false);
conn.setAutoCommit(false);

47
47
47
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Transactions
transaCtIons

means
meansthatthataatransaction
transactionisisstarting.
starting.The
Thenext
nextstatement
statementcreates
createsan
anArrayList
ArrayListand
andisisexplained
explained
shortly.
shortly.Next,
Next,isiscreated
createdaaPreparedStatement,
PreparedStatement,which whichrepresents
representsaaSQLSQLcommand
commandthat thatinserts
inserts
aa row
row inin the
the table
table history,
history, but
but only
only insert
insert values
values inin the
the columns
columns name
name and
and title.
title. Then
Then the
the
method
methodperforms
performsthreethreecalls
callsofofaamethod
methodinsert(),
insert(),which
whichinserts
insertsaarow
rowininthe
thetable.
table.IfIfititgoes
goes
well,
well, aa commit()
commit() isis performed,
performed, andand the
the three
three insertions
insertions ofof rows
rows are
are permanent
permanent inserted
inserted inin
the
thedatabase.
database.If, If,however,
however,oneoneofofthe
thethree
threeinsert()
insert()raises
raisesaaSQLException,
SQLException,the thecatch
catchblock
blockisis
performed
performed and and executes
executes aa rollback(),
rollback(), which
which means
means that
that the
the database
database operations
operations performed
performed
after
afterthe
thestart
startofofthe
thetransaction
transactionisisrolled
rolledback
backandandthe thedatabase
databasehashasthe
thesame
samecondition
conditionasas
before
beforethe thetransaction
transactionwas wasstarted.
started.

Then
Thenthere
thereisisthe
themethod
methodinsert():
insert():

private static void insert(PreparedStatement


stmt, String navn, String titel,
ArrayList<Integer> list) throws SQLException
{
prepareStatement(stmt, navn, titel);
stmt.executeUpdate();
list.add(getId(stmt));
}

Copenhagen
Master of Excellence cultural studies
Copenhagen Master of Excellence are
two-year master degrees taught in English
at one of Europe’s leading universities religious studies

Come to Copenhagen - and aspire!

Apply now at science


www.come.ku.dk

48
48
JAVA
JAVA 6:
JAVA 6: JDBC
6: JDBC AND
JDBC AND DATABASE
AND DATABASE APPLICATIONS
DATABASE APPLICATIONS
APPLICATIONS transaCtIons
Transactions
transaCtIons

The method
The method performs
performs aa call
call to
to aa method
method that
that inserts
inserts the
the values
values for
for the
the parameters
parameters inin stmt,
stmt,
and then the
and then the statement
statement isis executed.
executed. The
The primary
primary key
key of
of the
the table
table history
history isis an
an auto-generated
auto-generated
Integer,
Integer, and
and sometimes
sometimes youyou need
need to
to know
know the
the id
id when
when aa row
row isis assigned.
assigned. ThisThis can
can be
be done
done
in several
in several ways,
ways, but
but I’ve
I’ve written
written aa little
little method
method forfor this
this purpose:
purpose:

private
private static
static int
int getId(Statement
getId(Statement stmt)
stmt) throws
throws SQLException
SQLException
{
{
ResultSet res
ResultSet res =
= stmt.executeQuery("SELECT
stmt.executeQuery("SELECT LAST_INSERT_ID()");
LAST_INSERT_ID()");
res.next();
res.next();
return res.getInt(1);
return res.getInt(1);
}
}

Here
Here isis LAST_INSERT_ID()
LAST_INSERT_ID() aa function
function in
in MySQL,
MySQL, which
which returns
returns the
the last
last assigned
assigned auto-
auto-
generated
generated ID.
ID. These
These keys
keys are
are in
in this
this example
example added
added to
to an
an ArrayList
ArrayList that
that isis not
not used
used for
for
anything,
anything, but
but itit does
does in
in the
the next
next example,
example, and
and here
here you
you must
must mainly
mainly observe
observe howhow to
to grab
grab
an
an auto
auto generated
generated key.
key.

If
If one
one executes
executes the the above
above test
test method,
method, the the last
last INSERT
INSERT fails,
fails, since
since there
there isis no
no value
value for
for
the
the column
column name,name, and
and in
in the
the database
database isis defined
defined that
that this
this column
column must
must have
have aa value.
value. That
That
is,
is, there
there isis aa rool
rool back.
back. If
If you
you open
open MySQL
MySQL Workbench,
Workbench, youyou can
can easily
easily convince
convince yourself
yourself
that
that the
the rows
rows are are not
not inserted.
inserted.

The
The example
example shows
shows basically
basically what
what there
there isis to
to say
say about
about transactions,
transactions, but
but there
there isis also
also aa
possibility
possibility to
to define
define aa Savepoint,
Savepoint, which
which cancan bebe used
used to
to indicate
indicate that
that not
not all
all operations
operations
has
has to
to be
be rolled
rolled back.
back. Consider
Consider the
the following
following test
test method,
method, which
which isis an
an extension
extension of of the
the
above
above method:
method:

private
private static
static void
void test10()
test10()
{
{
Connection conn
Connection conn == null;
null;
Savepoint
Savepoint point = null;
point = null;
try
try
{
{
conn =
conn = DriverManager.getConnection(
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false",
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa",
"pa", "Volmer_1234");
"Volmer_1234");
conn.setAutoCommit(false);
conn.setAutoCommit(false);
ArrayList<Integer>
ArrayList<Integer> list
list == new
new ArrayList();
ArrayList();
PreparedStatement stmt1
PreparedStatement stmt1 == conn.prepareStatement(
conn.prepareStatement(
"INSERT
"INSERT INTO
INTO history
history (name,
(name, title)
title) VALUES
VALUES (?,
(?, ?)");
?)");
PreparedStatement stmt2
PreparedStatement stmt2 == conn.prepareStatement(
conn.prepareStatement(
"UPDATE
"UPDATE history
history SET
SET country
country = = ?
? WHERE
WHERE id
id == ?");
?");
insert(stmt1, "Egil
insert(stmt1, "Egil Skallegrimson",
Skallegrimson", null,
null, list);
list);
insert(stmt1,
insert(stmt1, "Knud
"Knud Larvard",
Larvard", "Duke",
"Duke", list);
list);

49
49
49
JAVA 6: JDBC AND DATABASE APPLICATIONS Transactions
JAVA 6: JDBC AND DATABASE APPLICATIONS transaCtIons

insert(stmt1, "Skipper Clement", "Rebel", list);


conn.commit();
point = conn.setSavepoint();
update(stmt2, "DK", list.get(1));
update(stmt2, "DK", list.get(2));
update(stmt2, "Island", list.get(0));
conn.commit();
}
catch(SQLException ex)
{
if (conn != null)
try
{
if (point == null) conn.rollback(); else conn.rollback(point);
} catch (Exception ex2) {}
System.out.println(ex);
}
finally
{
try { if (conn != null) conn.close(); } catch (SQLException ex) {}
}
}

The first
The first part
part is
is basically
basically thethe same
same as as the
the method
method test09(),
test09(), except
except that
that there
there is is defined
defined anan
additional PreparedStatement
additional PreparedStatement to to aa SQL
SQL UPDATE.
UPDATE. Furthermore,
Furthermore, there there isis defined
defined aa name
name
for the
for the last
last INSERT,
INSERT, suchsuch it it will
will notnot fails.
fails. After
After the
the three
three inserts()
inserts() methods
methods are are performed,
performed,
the test
the test method
method performs
performs aa commit()
commit() and and defines
defines aa Savepoint,
Savepoint, indicating
indicating that that upup to
to this
this
point of
point of the
the transaction
transaction the the statements
statements are are executed
executed correct.
correct. Next,
Next, the
the method
method update()
update() isis
executed for
executed for each
each ofof the
the three
three rows
rows that
that are
are inserted
inserted in in the
the table.
table. The
The method
method updates
updates the
the
column country
column country andand it
it is
is here
here that
that II uses
uses the
the keys
keys that
that areare stored
stored inin the
the list.
list. Here
Here are
are the
the
first two
first two update()
update() done
done correctly,
correctly, but but the
the last
last one
one raises
raises aa SQLException
SQLException when when the the column
column
country only
country only has
has room
room forfor two
two characters.
characters. TheThe result
result is is that
that control
control is is transferred
transferred to to the
the
catch block,
catch block, which
which perform
perform aa rollback,
rollback, butbut when
when the the Savepoint
Savepoint object
object isis not
not null,
null, one
one can
can
conclude that
conclude that the
the Savepoint
Savepoint is is reached,
reached, andand thus
thus the
the three
three insert()
insert() methods
methods are are performed
performed
without error.
without error. Therefore
Therefore is is only
only rolled
rolled back
back from
from thethe Savepoint.
Savepoint. If If you
you examine
examine the the table
table
in MySQL
in MySQL Workbench
Workbench you you will
will see
see that
that the
the three
three INSERT
INSERT statements
statements areare executed,
executed, butbut the
the
three UPDATE
three UPDATE statements
statements are are not.
not.

50

50
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Transactions
transaCtIons

6.1
6.1 BACH
BACH UPDATES
UPDATES
As
As aa last
last thing
thing concerning
concerning JDBC and database operations, I will mentionmention batch
batch updates.
updates.
IfIf you
you have
have toto perform
perform many
many database operations – such as many INSERT
INSERT statements
statements –– itit
may
may take
take aa long
long time,
time, ifif the
the program calls the database for each statement.
statement. You
You can
can then
then
gather
gather all
all operations
operations in
in aa batch,
batch, which is possible for a Statement, a PreparedStatement
PreparedStatement and
and
aa CallableStatement,
CallableStatement, andand then
then performs all operations at once with a single
single connection
connection toto
the
the database.
database. The
The following
following test method shows the syntax:

private static void test11()


{
List<Person> list = createKings();
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234"))
{
PreparedStatement stmt1 =
conn.prepareStatement("DELETE FROM history WHERE name LIKE ?");
PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO history
(name, title, birth, death, country, description) VALUES (?, ?, ?, ?, ?, ?)");

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

51
51
JAVA 6: JDBC AND DATABASE APPLICATIONS Transactions
JAVA 6: JDBC AND DATABASE APPLICATIONS transaCtIons

DatabaseMetaData metaData = conn.getMetaData();


if (metaData.supportsBatchUpdates())
{
for (Person pers : list)
{
stmt1.setString(1, pers.getName());
stmt1.addBatch();
}
for (Person pers : list)
{
prepareStatement(stmt2, pers);
stmt2.addBatch();
}
stmt1.executeBatch();
stmt2.executeBatch();
}
else System.out.println("This database does not support batch updates");
}
catch (SQLException ex)
{
System.out.println(ex);
}
}

createKings() isis aa method


createKings() method that,
that, inin principle,
principle, isis identical
identical to to createPersons()
createPersons() (it
(it creates
creates just
just
some other
some other Person
Person objects).
objects). Inside
Inside the
the try
try block
block the
the method
method createscreates two
two PreparedStatement
PreparedStatement
objects respectively
objects respectively aa DELETE
DELETE and and an
an INSERT.
INSERT. Since
Since itit isis not
not aa requirement
requirement that that JDBC
JDBC
supports batch
supports batch updates,
updates, isis isis first
first tested
tested whether
whether that
that isis the
the case,
case, and
and ifif so
so aa loop
loop ofof all
all
the objects
the objects inin the
the list,
list, add
add statements
statements to to delete
delete the
the corresponding
corresponding rows, rows, ifif they
they exist,
exist, but
but
instead of
instead of performing
performing excecuteUpdate()
excecuteUpdate() isis performed
performed an an addBatch(),
addBatch(), which which adds
adds that
that database
database
operations to
operations to aa list
list of
of operations
operations in in the
the object
object stmt1.
stmt1. Subsequently,
Subsequently, the the same
same happens
happens forfor
all objects
all objects in
in the
the list,
list, but
but this
this time
time asas stmt2
stmt2 objects.
objects. So
So far,
far, the
the database
database operations
operations areare not
not
performed, but
performed, but itit happens
happens eventually
eventually with
with the
the method
method executeBatch().
executeBatch().

52

52
JAVA
JAVA6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Transactions
transaCtIons

EXERCISE
EXERCISE 44
The
The following
following lines
lines show
show the
the country
country code,
code, code
code for
for the
the continent,
continent, the
the country’s
country’s area
area and
and
size
size of
of population
population of
of seven
seven countries:
countries:

AF;AS;652225;28150000
AL;EU;28748;3100112
DZ;AF;2381740;32531853
AS;NA;199;57902
US;NA;9826675;310322000
AD;EU;467.63;85458
AO;AF;1246700;18565269

You must
You must write
write aa program
program that
that updates
updates the
the table
table country
country with
with the
the information
information above
above when
when

1. itit must
1. must be
be done
done with
with aa batch
batch update
update
2. you
2. you must
must use
use aa Statement
Statement object
object instead
instead of
of aa PreparedStatement
PreparedStatement object
object

Note that
Note that the
the method
method addBatch()
addBatch() may
may have
have aa SQL
SQL expression
expression asas aa parameter.
parameter.

Afterthe
After thetable
tableisisupdated,
updated,you
youmust mustperform
performaaSQL
SQLSELECT
SELECTthat thatextracts
extractsthethename
nameof
ofthe
the
countries in
countries in which
which thethe area
area isis not
not NULL,
NULL, and
and prints
prints the
the names
names on
on the
the screen.
screen.

53
53
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable

7 THE COMPONENT JTABLE


This chapter describes one of the most complex Swing components called JTable. In principle,
it has not something with JDBC or databases to do, but the component is intended to
display data organized in rows and columns, and therefore the component finds specific
application to display the contents of database tables. This is the reason why it is referred
to at this place.

It is a very important component, it is very flexible with many options and customizations,
but it is equally complex and it is not always so easily to figure out how it works. The class
name is as mentioned JTable, and first of all it is important to note, that a JTable object does
not contains data, but it can display data defined by a data model. The class uses several
(actually many) helper classes that are commonly found in the package javax.swing.table.

Trust and responsibility


NNE and Pharmaplan have joined forces to create – You have to be proactive and open-minded as a
NNE Pharmaplan, the world’s leading engineering newcomer and make it clear to your colleagues what
and consultancy company focused entirely on the you are able to cope. The pharmaceutical field is new
pharma and biotech industries. to me. But busy as they are, most of my colleagues
find the time to teach me, and they also trust me.
Inés Aréizaga Esteva (Spain), 25 years old Even though it was a bit hard at first, I can feel over
Education: Chemical Engineer time that I am beginning to be taken seriously and
that my contribution is appreciated.

NNE Pharmaplan is the world’s leading engineering and consultancy company


focused entirely on the pharma and biotech industries. We employ more than
1500 people worldwide and offer global reach and local knowledge along with
our all-encompassing list of services. nnepharmaplan.com

54
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS The
thecomponent
ComponentJTable
JtaBle

7.1
7.1 THE
THEDEMO
DEMOPROGRAM
PROGRAM
I’ll
I’llstart
startsimple,
simple,and
andbelow
belowshows
showsaawindow
windowwith
withaaJTabel
JTabelthat
thatshows
showssome
somedata
datalaid
laidout
out
ininaatable
tablewith
with66columns
columnsand
andnine
ninerows:
rows:

The
Theindividual
individualdata
dataelements
elementsare
arenot
notimportant,
important,but
butthey
theyshow
showdata
dataabout
about99books.
books.IfIfyou
you
run
runthe
theprogram,
program,you
youmust
mustobserve
observethe
thefollowing:
following:

--- You
Youcan canchange
changethe thewindow
windowsize.size.IfIfyou
youchanges
changesthetheheight,
height,sosothere
thereisisno
noroom
room
for
forthetheentire
entiretable,
table,you
youget
getaascrollbar.
scrollbar.IfIfyou
youchanges
changesthethethe
thewidth,
width,thethecolumn
column
widths
widthsarearechanged,
changed,but butthere
thereisisno
noscrollbar.
scrollbar.However,
However,the thewidth
widthofofthe
thetwo
twocolumns
columns
for
forISBN
ISBNandandPages
Pagesdo donot
notchange.
change.
--- ItItisispossible
possibletotoselect
selectmultiple
multiplerowsrowsby byclicking
clickingwith
withthe
themouse,
mouse,andandthere
thereare
arethe
the
usual
usualfeatures
featuresthat
thatapply
applyinincombination
combinationwith withCtrl
Ctrland
andShift
Shiftkeys.
keys.
--- You
You cancan change
change thethe width
width ofof each
each column
column byby dragging
dragging the
the divider
divider between
between twotwo
column
columnheaders.
headers.
--- You
Youcan canedit
editthe
thecontents
contentsofofthetheindividual
individualcells.
cells.You
Youopens
opensaacell
cellfor
forediting
editingby by
double-clicking
double-clickingwith withthe
themouse.
mouse.

There
There are
are soso many
many attached
attached functions
functions toto aa JTable,
JTable, and
and what
what isis mentioned
mentioned above
above isis the
the
default
defaultsettings
settings(except
(exceptthe
thetwo
twocolumns
columnsthatthathave
havefixed
fixedwidth).
width).

The
Thecode
codeisisasasfollows:
follows:

package jtabledemo;

import javax.swing.*;
import java.awt.*;
import javax.swing.table.*;

55
55
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

public class Demo01 extends JDialog


{
private String[] colNames =
{ "Isbn", "Titel", "Edition", "Published", "Pages", "Lent" };
private Object[][] data = {
{ "0-672-32584-5", "MySQL Tutorial", 1, 2004, 267, false },
{ "978-1-59059-855-9", "Beginning Fedora, From Novice to Professional", 1,
2005, 519, false },
{ "978-9935-9198-1-6", "Islændingesagaerne bind I", 1, 2014, 440, true },
{ "978-9935-9198-2-3", "Islændingesagaerne bind II", 1, 2014, 501, true },
{ "978-9935-9198-3-0", "Islændingesagaerne bind III", 1, 2014, 501, true },
{ "978-9935-9198-4-7", "Islændingesagaerne bind IV", 1, 2014, 507, true },
{ "978-9935-9198-5-4", "Islændingesagaerne bind V", 1, 2014, 531, true },
{ "978-0-13-255317-9", "Computer Networkks", 5, 2011, 951, false },
{ "978-87-02-15535-8", "Toscana, Maden, vinen, kulturen & landskabet", 1, 2014,
329, true }
};

public Demo01()
{
super(null, "Demo01", JDialog.ModalityType.APPLICATION_MODAL);
setSize(750, 300);
this.setLocationRelativeTo(null);
setLayout(new BorderLayout());
add(new JScrollPane(createTable()));
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}

private JTable createTable()


{
JTable table = new JTable(data, colNames);
setColumnWidth(table.getColumnModel().getColumn(0), 130);
setColumnWidth(table.getColumnModel().getColumn(4), 50);
return table;
}

private void setColumnWidth(TableColumn col, int width)


{
col.setPreferredWidth(width);
col.setMinWidth(width);
col.setMaxWidth(width);
}
}

56
56
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable

In the beginning of the code is laid out the data to be displayed. The first array is the
column headings, while the next two-dimensional array is the table’s data. You should note
that the array’s data is of the type Object, and since some of the data are simple data types
there are used auto boxing for objects to type Integer and Boolean. The table is created in
the method createTable() where the two data structures (arrays) are sent as parameters to
the constructor in JTabel and the constructor will then based on these structures create a
data model. Next is called the method setColumnWidth() for column 0 and column 4 to
define a fixed width for these columns. When looking at the syntax, there is not much
mystery in it, but it is far from a typical application, and take the many opportunities for
user interaction into account is clear that there is a part that must be learned.

The class is part of a project called JTableDemo and when you run the program, you get
the following window:

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

57
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

and
andthus
thusaawindow
window with
with 12
12 buttons.
buttons. EachEach button
button opens
opens aa dialog
dialog box,
box, showing
showing an
an example
example
ofofaaJTable,
JTable, and
and the
the upper
upper left
left isis the
the example
example mentioned above.
mentioned above.

THE
THEDATA
DATAMODEL
MODEL
I Iwill
willnow
now look
look atat the
the data
data model
model as
as aa JTable displays the objects
objects in
in aa data
data model.
model. In
In the
the
previous
previous example
example itit waswas the
the constructor
constructor of the class JTable that
that created
created the
the model,
model, butbut
typically
typicallyitithappens
happens otherwise.
otherwise. AA data
data model
model is a class that inherits
inherits AbstractTableModel,
AbstractTableModel,andand
aamodel
modelforfor the
the same
same data
data as
as above
above could
could be:

package jtabledemo;

import javax.swing.table.*;

public class DemoDataModel extends AbstractTableModel


{
private String[] colNames =
{ "Isbn", "Titel", "Edition", "Published", "Pages", "Lent" };
private Object[][] data = {
{ "0-672-32584-5", "MySQL Tutorial", 1, 2004, 267, false },
{ "978-1-59059-855-9", "Beginning Fedora, From Novice to Professional", 1,
2005, 519, false },
{ "978-9935-9198-1-6", "Islændingesagaerne bind I", 1, 2014, 440, true },
{ "978-9935-9198-2-3", "Islændingesagaerne bind II", 1, 2014, 501, true },
{ "978-9935-9198-3-0", "Islændingesagaerne bind III", 1, 2014, 501, true },
{ "978-9935-9198-4-7", "Islændingesagaerne bind IV", 1, 2014, 507, true },
{ "978-9935-9198-5-4", "Islændingesagaerne bind V", 1, 2014, 531, true },
{ "978-0-13-255317-9", "Computer Networkks", 5, 2011, 951, false },
{ "978-87-02-15535-8", "Toscana, Maden, vinen, kulturen & landskabet", 1, 2014,
329, true }
};

58
58
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable

JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

public DemoDataModel()
{
super();
}

public int getColumnCount()


{
return colNames.length;
}

public int getRowCount()


{
return data.length;
}

public String getColumnName(int col)


{
return colNames[col];
}

public Object getValueAt(int row, int col)


{
return data[row][col];
}

public Class getColumnClass(int c)


{
return getValueAt(0, c).getClass();
}

public boolean isCellEditable(int row, int col)


{
return col > 2;
}

public void setValueAt(Object value, int row, int col)


{
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}

59
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable

that in addition to the data definitions alone is overriden methods from the base class.
In fact, only three of these methods are necessary (getColumnCount(), getRowCount() and
getValueAt()) because the others have default implementations in AbstractTableModel. However
getColumnName() is necessary to get the correct column names. The methods are generally
simple, but you should note the method isCellEditable(), which in this case defines that only
columns with index greater than 2 can be edited. Note also the method getColumnClass(),
which returns the data type of each column. In general (as in the previous example), a
JTable display the value of a datalement as a string in the form of toString(), but with the
data type available, the cells will be rendered differently. For example the cells containing
the numerical values show the content right justified, and as another example, a Boolean
(the last column in this case) is displayed as a JCheckBox component.

Below is a window showing a JTable on the basis of the above data model. The example
should show two things:

1. how to apply a data model


2. how the selection of rows and columns in JTabel works

The first is very simple, while the selection of cells is a little more difficult to figure out.

Sharp Minds - Bright Ideas!


Employees at FOSS Analytical A/S are living proof of the company value - First - using The Family owned FOSS group is
new inventions to make dedicated solutions for our customers. With sharp minds and the world leader as supplier of
cross functional teamwork, we constantly strive to develop new unique products - dedicated, high-tech analytical
Would you like to join our team? solutions which measure and
control the quality and produc-
FOSS works diligently with innovation and development as basis for its growth. It is tion of agricultural, food, phar-
reflected in the fact that more than 200 of the 1200 employees in FOSS work with Re- maceutical and chemical produ-
search & Development in Scandinavia and USA. Engineers at FOSS work in production, cts. Main activities are initiated
development and marketing, within a wide range of different fields, i.e. Chemistry, from Denmark, Sweden and USA
Electronics, Mechanics, Software, Optics, Microbiology, Chemometrics. with headquarters domiciled in
Hillerød, DK. The products are
We offer marketed globally by 23 sales
A challenging job in an international and innovative company that is leading in its field. You will get the companies and an extensive net
opportunity to work with the most advanced technology together with highly skilled colleagues. of distributors. In line with
the corevalue to be ‘First’, the
Read more about FOSS at www.foss.dk - or go directly to our student site www.foss.dk/sharpminds where
company intends to expand
you can learn more about your possibilities of working together with us on projects, your thesis etc.
its market position.

Dedicated Analytical Solutions


FOSS
Slangerupgade 69
3400 Hillerød
Tel. +45 70103370

www.foss.dk

60
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS The
thecomponent
ComponentJTable
JtaBle

InInaddition
additiontotothe
thetable,
table,the
thewindow
windowhashassome
someradio
radiobuttons
buttonsand
andcheckboxes,
checkboxes,sosothe
theuser
user
can specify how the selection of cells works. If you click in the table, it displays a message
can specify how the selection of cells works. If you click in the table, it displays a message
box
boxthat
thattells
tellswhat
whatisisclicked:
clicked:

You
Youare
areencouraged
encouragedtotorun
runthetheprogram,
program,sosoyou
youget
getan
anidea
ideaofofhow
howthe
theselection
selectionofofcells
cells
works
worksdepending
dependingon
onthethesettings
settingsofofthe
theprogram’s
program’sbuttons.
buttons.

The
Thefollowing
followingmethod
methodcreates
createsthe
thetable,
table,and
andyou
youmust
mustmainly
mainlyobserve
observehow
howtotomap
mapthe
thedata
data
model, which is done with a parameter to the constructor:
model, which is done with a parameter to the constructor:

private JTable createTable()


{
table = new JTable(new DemoDataModel());
table.setFillsViewportHeight(true);
table.getSelectionModel().addListSelectionListener(new RowListener());
table.getColumnModel().getSelectionModel().addListSelectionListener(
new ColumnListener());
return table;
}

6161
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable

The next statement is not really necessary, but it means that a JTable component fills the part
of the container that is not used for other components, and thus the white space between
the table and the bottom components are part of the JTable component. For example, it
could be important if the program uses drag and drop. The last two statements are related
to event handlers, respectively selection of rows and columns, that among other things,
opens a message box as shown above. The goal of this event handling is to show how to
catch events concerning selection of rows and columns and including which cell is clicked.

The rest of the program code fills a part, but contains nothing new. A part of the code
concerning the design of the user interface, where the components are laid out with a
BoxLayout. Moreover, there are event handlers for each of the 6 buttons, and when the
three check boxes is not independent of each other, the program must implement a logic
that controls when a check box must be selected.

EDIT CELLS

As mentioned in the first example, you can immediately edit the contents of the cells (if
permitted according to the data model, which means that in this case you can not edit the
contents of the first three columns). It is an example of a window with a JTabel showing
the same data model as in the previous example. Here you can edit a cell by double-clicking
on it:

62
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable

and if you then leave the cell (for example by pressing Enter), you get a message box that
tells that the cell is changed:

The content of the cell should in this case (the model) be an integer, and if you enter
something that is not an integer and press Enter, the cell will be selected, which shows that
the content is illegal (see below).

This is the standard error handling, but I show later, how you can control the editing of
cells, and what should happens if you enter something illegal.

63
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS The
thecomponent
ComponentJTable
JtaBle

With
With regard
regard to
to the
the code
code there
there isis not
not much
much to
to explain,
explain, and
and the
the most
most important
important isis to
to show
show
how
how to
to assign
assign an
an event
event handler
handler that
that captures
captures changes
changes to
to the
the table:
table:

private JTable createTable()


{
JTable table = new JTable(new DemoDataModel());
table.getModel().addTableModelListener(new TableChangedListener());
return table;
}

class TableChangedListener implements TableModelListener


{
public void tableChanged(TableModelEvent e)
{
int row = e.getFirstRow();
int col = e.getColumn();
DemoDataModel model = (DemoDataModel)e.getSource();
String name = model.getColumnName(col);
Object value = model.getValueAt(row, col);
JOptionPane.showMessageDialog(Demo03.this, name + ": " + value);
}
}

Here
Hereyou
youparticularly
particularlyshould
shouldnote
notehow
howto
toreferences
referencesthe
thecell
cellthat
thatisismodified,
modified,including
includingits
its
content.
content.

As
As mentioned,
mentioned, you
you can
can associates
associates an
an editor
editor for
for editing
editing the
the individual
individual cells,
cells, asas you
you do
do in
in
the following way:
the following way:

table.getColumnModel().getColumn(3).setCellEditor(new IntegerEditor(1000, 2100));

64
64
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS The
the component
Component JTable
JtaBle

where is assigned a CellEditor to the third column (the column of the year), which requires
that the value must be an integer between 1000 and 2100. When you edit the content of
a cell, the content of the cell are copied into a corresponding JTextField where you can edit
it. In this case there is only attached a CellEditor to column 3, and so you can edit the
content of the column 4 (the number of pages) as default. Below is a window where the
page number is changed and the cell for a year is editing. Now if you press Enter, you get
the following message box that says that you have entered an illegal value:

If you here click Alter, you can continue to edit the cell, and if you click Cancel, the old
value is inserted again.

A CellEditor is a class that inherits DefaultCellEditor, which in turn inherits JTextField. In


this example, the editor is written as follows:

class IntegerEditor extends DefaultCellEditor


{
JFormattedTextField field;
NumberFormat format;
private Integer min, max;

public IntegerEditor(int min, int max)


{
super(new JFormattedTextField());
field = (JFormattedTextField)getComponent();

65
65
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

this.min = min;
this.max = max;
format = NumberFormat.getIntegerInstance();
NumberFormatter formatter = new NumberFormatter(format);
formatter.setFormat(format);
formatter.setMinimum(min);
formatter.setMaximum(max);
field.setFormatterFactory(new DefaultFormatterFactory(formatter));
field.setValue(min);
field.setHorizontalAlignment(JTextField.TRAILING);
field.setFocusLostBehavior(JFormattedTextField.PERSIST);
field.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "check");
field.getActionMap().put("check", new CheckAction());
}

public Component getTableCellEditorComponent(JTable table, Object value,


boolean isSelected, int row, int column)
{
JFormattedTextField field =
(JFormattedTextField)super.getTableCellEditorComponent(
table, value, isSelected, row, column);
field.setValue(value);
return field;
}

The Wake
the only emission we want to leave behind

.QYURGGF'PIKPGU/GFKWOURGGF'PIKPGU6WTDQEJCTIGTU2TQRGNNGTU2TQRWNUKQP2CEMCIGU2TKOG5GTX

6JGFGUKIPQHGEQHTKGPFN[OCTKPGRQYGTCPFRTQRWNUKQPUQNWVKQPUKUETWEKCNHQT/#0&KGUGN6WTDQ
2QYGTEQORGVGPEKGUCTGQHHGTGFYKVJVJGYQTNFoUNCTIGUVGPIKPGRTQITCOOGsJCXKPIQWVRWVUURCPPKPI
HTQOVQM9RGTGPIKPG)GVWRHTQPV
(KPFQWVOQTGCVYYYOCPFKGUGNVWTDQEQO

66
66
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

public Object getCellEditorValue()


{
JFormattedTextField field = (JFormattedTextField)getComponent();
Object value = field.getValue();
if (value instanceof Integer) return value;
else if (value instanceof Number)
return new Integer(((Number)value).intValue());
else
{
try
{
return format.parseObject(value.toString());
}
catch (ParseException exc)
{
return null;
}
}
}

public boolean stopCellEditing()


{
JFormattedTextField field = (JFormattedTextField)getComponent();
if (field.isEditValid())
{
try
{
field.commitEdit();
}
catch (java.text.ParseException exc)
{
}
}
else
{
if (!revert()) return false;
}
return super.stopCellEditing();
}

protected boolean revert()


{
Toolkit.getDefaultToolkit().beep();
field.selectAll();
Object[] options = {"Alter", "Cancel" };
if (JOptionPane.showOptionDialog(SwingUtilities.getWindowAncestor(field),
"The value .... ", "Illegal value", JOptionPane.YES_NO_OPTION,

67
67
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

JOptionPane.ERROR_MESSAGE, null, options, options[1]) == 1)


{
field.setValue(field.getValue());
return true;
}
return false;
}

class CheckAction extends AbstractAction


{
public void actionPerformed(ActionEvent e)
{
if (!field.isEditValid())
{
if (revert()) field.postActionEvent();
}
else
try
{
field.commitEdit();
field.postActionEvent();
}
catch (java.text.ParseException exc)
{
}
}
}
}

It is
It is aa comprehensive
comprehensive class,
class, simply
simply because
because it
it is
is complex
complex to
to edit
edit the
the content
content of
of aa field.
field.
Essentially the
Essentially the following
following happens:
happens:

The class
The class inherits
inherits DefaultCellEditor
DefaultCellEditor and and thus
thus specifically
specifically aa JTextField.
JTextField. The
The constructor
constructor has
has
two parameters,
two parameters, similar
similar to
to that
that you
you have
have to to edit
edit aa number
number within
within aa range.
range. The
The constructor
constructor
starts to
starts to replace
replace its
its editing
editing component
component (which(which is is aa JTextField )
JTextField ) with
with another
another Swing
Swing component
component
called aa JFormattedTextField,
called JFormattedTextField, that that is
is aa JTextField
JTextField that that has
has an
an associated
associated object,
object, which
which can
can
format the
format the text
text entered.
entered. In
In this
this case
case it
it is
is aa NumberFormatter
NumberFormatter object object that
that is
is initialized
initialized with
with
aa NumberFormat
NumberFormat object object for
for formatting
formatting integers
integers and and the
the range
range within
within which
which the the number
number
must lie.
must lie. Then
Then isis defined
defined that
that the
the field
field should
should be be right
right justified,
justified, and
and anan event
event handler
handler to
to
the Enter
the Enter key
key is
is added,
added, such
such you
you returns
returns fromfrom thethe field
field when
when youyou hit
hit the
the Enter
Enter key.
key.

68
68
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS The
the component
Component JTable
JtaBle

The event
The event handler
handler isis defined
defined as
as an
an inner
inner class.
class. It
It begins
begins by
by testing
testing whether
whether the
the content
content of
of
the
the field
field is
is legal
legal in
in relation
relation toto the
the formatter,
formatter, and
and is
is it
it not
not the
the case,
case, the
the method
method revert() is
revert() is
called.
called. It
It is
is the
the method
method that that displays
displays the
the above
above message
message box
box where
where you
you can
can choose
choose whether
whether
you
you want to change the entered value, or cancel and return to the old content. If you choose
want to change the entered value, or cancel and return to the old content. If you choose
the last,
the last, the
the handler
handler isis terminated
terminated with
with aa postActionEvent().
postActionEvent(). IsIs the
the content
content of
of the
the field
field legally,
legally,
the
the result
result isis marked
marked as as commited,
commited, andand again
again finish
finish with
with aa postActionEvent().
postActionEvent().

The
The class
class has
has three
three other
other methods.
methods. The
The first
first

getTableCellEditorComponent(JTable table, Object value, boolean isSelected,


int row, int column)

returns the component (the input field) that is assigned to a particular cell and assign it a
value, while the next

Object getCellEditorValue()

returns the object which is currently edited as an Integer object. Finally the last method
that is performed when editing ends.

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57

69
69
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable

RENDERING CELLS

A CellEditor allows you to define how the content of cells in a JTable can be edited, but
a column can also be associated with a CellRenderer that indicates how the content of the
column’s cells should appear. As already mentioned the default is as a string in which the
cell shows an object as the result of its toString() method, but if a JTable is defined on the
basis of a TableModel and implements the method getColumnClass(), it is instead the objects’
data type, which determines how the values appear. For example becomes a Boolean type
shown – or rendered – as a JCheckBox. How each column should render their cells values
can also be defined with a CellRenderer, which is a class that defines how.

Consider the above window, which has a JTable showing the same data model as above.
Here you should note

-- if you clicks on a cell in the column Published, you get a combo box from which
you can select a date
-- a cell in the column Pages appears as a button, and if you clicks the button, you
get a message box as shown below
-- the last column shows not only a check box, but also a text

70
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS The
thecomponent
ComponentJTable
JtaBle
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

The
Thereason
reasonisisthat
thatthere
thereisisassociated
associatedaaCellRenderer
CellRendererforforeach
eachofofthe
thelast
lastthree
threecolumns.
columns.For
For
The
the reason is that there is associated a CellRenderer for each of the last three columns. For
thecolumn
columnPublished
Publishedthe
therenderer
rendererisisdefined
definedititasasfollows:
follows:
the column Published the renderer is defined it as follows:
public void setYearColumn(JTable table, TableColumn column)
public void setYearColumn(JTable table, TableColumn column)
{
{
JComboBox comboBox = new JComboBox();
JComboBox comboBox = new JComboBox();
for (int i = 1950; i <= 2025; ++i) comboBox.addItem(i);
for (int i = 1950; i <= 2025; ++i) comboBox.addItem(i);
column.setCellEditor(new DefaultCellEditor(comboBox));
column.setCellEditor(new DefaultCellEditor(comboBox));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Klik for at åbne dropdown boks");
renderer.setToolTipText("Klik for at åbne dropdown boks");
renderer.setHorizontalAlignment(JLabel.RIGHT);
renderer.setHorizontalAlignment(JLabel.RIGHT);
column.setCellRenderer(renderer);
column.setCellRenderer(renderer);
}
}

Thiscreates
This creates a usualJComboBox
JComboBox componentthat that is initializedwith
with a yearbetween
between 1950and and
This createsaausual
usual JComboBoxcomponent
component thatisisinitialized
initialized withaayear
year between19501950 and
2025.ItItcan
2025. can thenbe be directlyassigned
assigned to thecolumn
column as a CellEditor,which
which meansthatthat if you
2025. It canthen
then bedirectly
directly assignedtotothe
the columnasasaaCellEditor,
CellEditor, whichmeans
means thatififyou
you
double-clickaacell,
double-click cell,the
thecombo
comboboxboxisisopend,
opend,sosoyou
youcan
canchoose
chooseaadate.
date.InInaddition,
addition,there
thereisis
double-click a cell, the combo box is opend, so you can choose a date. In addition, there is
createdaaDefaultTableCellRenderer,
created DefaultTableCellRenderer, thathas has attachedaatooltip.
tooltip. TheDefaultTableCellRenderer
DefaultTableCellRenderer
created a DefaultTableCellRenderer,that that hasattached
attached a tooltip.The
The DefaultTableCellRenderer
isis thenassociated
isthen
associated thecolumn
then associatedthe
column as a CellRenderer.
the columnasasaaCellRenderer.
CellRenderer.

Thenthere
Then there is thecolumn
column Pageswhere
where thecontent
content shouldbe
be displayedasasaabutton.
button. Hereaa
Then thereisisthe
the columnPages
Pages wherethe
the contentshould
should bedisplayed
displayed as a button.Here
Here a
renderer
renderer is defined as follows:
rendererisisdefined
definedasasfollows:
follows:
public void setPageColumn(JTable table, TableColumn column)
public void setPageColumn(JTable table, TableColumn column)
{
{
column.setCellRenderer(new PageCells());
column.setCellRenderer(new PageCells());
column.setCellEditor(new PageCells());
column.setCellEditor(new PageCells());
}
}

class PageCells extends AbstractCellEditor


class PageCells extends AbstractCellEditor
implements TableCellEditor, TableCellRenderer
implements TableCellEditor, TableCellRenderer
{
{
public Component getTableCellEditorComponent
public Component getTableCellEditorComponent
(JTable table, Object value, boolean isSelected, int row, int column)
(JTable table, Object value, boolean isSelected, int row, int column)
{
{
return table.getCellRenderer(row, column).ge
return table.getCellRenderer(row, column).ge
tTableCellRendererComponent(table,
tTableCellRendererComponent(table,
value, isSelected, isSelected, row, column);
value, isSelected, isSelected, row, column);
}
}

public Object getCellEditorValue()


public Object getCellEditorValue()
{
{
return null;
return null;
}
}

7171
71
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

public Component getTableCellRendererComponent(JTable table, Object value,


boolean isSelected, boolean hasFocus, int row, int column)
{
AbstractAction action = new AbstractAction("Klik")
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(Demo05.this, "Antal sider: " + value);
}
};
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(new EmptyBorder(3, 3, 3, 3));
panel.add(new JButton(action));
return panel;
}
}

Technical training on
WHAT you need, WHEN you need it
At IDC Technologies we can tailor our technical and engineering
training workshops to suit your needs. We have extensive OIL & GAS
experience in training technical and engineering staff and ENGINEERING
have trained people in organisations such as General
ELECTRONICS
Motors, Shell, Siemens, BHP and Honeywell to name a few.
Our onsite training is cost effective, convenient and completely AUTOMATION &
customisable to the technical and engineering areas you want PROCESS CONTROL
covered. Our workshops are all comprehensive hands-on learning
experiences with ample time given to practical sessions and MECHANICAL
demonstrations. We communicate well to ensure that workshop content ENGINEERING
and timing match the knowledge, skills, and abilities of the participants.
INDUSTRIAL
We run onsite training all year round and hold the workshops on DATA COMMS
your premises or a venue of your choice for your convenience.
ELECTRICAL
For a no obligation proposal, contact us today POWER
at training@idc-online.com or visit our website
for more information: www.idc-online.com/onsite/

Phone: +61 8 9321 1702


Email: training@idc-online.com
Website: www.idc-online.com

72

72
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS The
thecomponent
ComponentJTable
JtaBle

This
Thistime
timeisisdefined
definedananinner
innerclass.
class.The
Theclass
classinherits
inheritsAbstratCellEditor
AbstratCellEditorand andimplements
implementsinterfaces
interfaces
totoboth
botha aCellEditor
CellEditorandanda aCellRenderer.
CellRenderer.TheThemethod
methodgetTableCellEditorComponent()
getTableCellEditorComponent()isisnot notasas
important
importantininthis thiscontext
contextandanddoes
doesnothing
nothingmore
morethanthantotoreturn
returnthethecurrent
currentCellEditor,
CellEditor,but
but
the
theimportant
importantthings
thingsare
arehappening
happeningininthethemethod
methodgetTableCellRendererComponent(),
getTableCellRendererComponent(),which which
returns
returnsthe
thecomponent
componentthat thatshould
shouldrender
renderthe
thecontents
contentsofofthe thecell.
cell.ItItstarts
startswith
withdefining
defininganan
Action,
Action,which
whichdisplays
displaysa amessage
messageboxboxwith
withthe
thevalue
valueforfornumber
numberofofpages.pages.Next
Nextisiscreated
created
a aJPanel
JPanelwith
witha abutton
buttonfor forthis
thisaction,
action,and
andthe
theresult
resultisisthat
thatthe
thecell
cellwill
willcontain
containa abutton,
button,
sosoyou
youalso
alsocancanclick
clickthe
thebutton.
button.YouYoushould
shouldnote
notethat
thattotobebepossible
possibletotoclick
clickthe
thebutton,
button,
the
thecolumn
columnmust mustininthethemodel
modelbebedefined
definedasaseditable.
editable.

The
Thelast
lastcolumn
columnwith
withthe
thecheck
checkboxboxworks
worksthe
thesame
sameway,
way,andandthe
thedifference
differenceisismainly
mainlythat
that
the
thepanel
panelcreated
creatediningetTableCellRendererComponent()
getTableCellRendererComponent()this thistime
timecontains
containstwotwocomponents.
components.
Since
Since itit should
should bebe possible
possible toto edit
edit the
the content
content –– put
put a a check
check mark
mark –– thethe method
method
getCellEditorValue()
getCellEditorValue()mustmustthis
thistime
timereturn
returna avalue
valuethat
thatmust
mustbebeinitialized
initializedininthe
themethod
method
getTableCellEditorComponent().
getTableCellEditorComponent().

The
Thetable
tableisiscreated
createdasasfollows,
follows,with
withallallthe
thecolumns
columnsexcept
exceptthe
thecolumn
columnfor
forthe
thetitle
titleare
are
assigned
assigneda afixed
fixedwidth:
width:

private JTable createTable()


{
JTable table = new JTable(new DemoDataModel());
table.setRowHeight(35);
setColumnWidth(table.getColumnModel().getColumn(0), 130);
setColumnWidth(table.getColumnModel().getColumn(2), 60);
setColumnWidth(table.getColumnModel().getColumn(3), 70);
setColumnWidth(table.getColumnModel().getColumn(4), 80);
setColumnWidth(table.getColumnModel().getColumn(5), 110);
setYearColumn(table, table.getColumnModel().getColumn(3));
setPageColumn(table, table.getColumnModel().getColumn(4));
setCheckColumn(table, table.getColumnModel().getColumn(5));
return table;
}

private void setColumnWidth(TableColumn col, int width)


{
col.setPreferredWidth(width);
col.setMinWidth(width);
col.setMaxWidth(width);
}

7373
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS The
the component
Component JTable
JtaBle

As
As another
another example
example of
of aa renderer
renderer displays
displays the
the following
following window
window the
the first
first two
two columns
columns with
with
aa different
different color:
color:

The
The code
code isis the
the following:
following:

package jtabledemo;

import javax.swing.*;
import java.awt.*;
import javax.swing.table.*;

public class Demo06 extends JDialog


{
public Demo06()
{
super(null, "Demo06", JDialog.ModalityType.APPLICATION_MODAL);
setSize(750, 400);
this.setLocationRelativeTo(null);
setLayout(new BorderLayout());
add(new JScrollPane(createTable()));
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}

74
74
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

private JTable createTable()


{
JTable table = new JTable(new DemoDataModel());
table.setDefaultRenderer(String.class, new ColorRenderer());
table.setRowHeight(30);
return table;
}
}

class ColorRenderer extends JLabel implements TableCellRenderer


{
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
{
setText(value.toString());
setForeground(column == 0 ? Color.red : Color.blue);
setFont(new Font("Liberation Serif", Font.PLAIN, 18));
setToolTipText(column == 0 ? "ISBN is red" : "Title is blue");
return this;
}
}

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

75
75
JAVA
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS the
the Component
Component JtaBle
JtaBle

The
The render
render object
object isis defined
defined by
by the
the class
class ColorRenderer
ColorRenderer and
and there
there isis not
not much
much to
to explain,
explain,
but you will notice how the render object is assigned in createTable():
but you will notice how the render object is assigned in createTable():

table.setDefaultRenderer(String.class,
table.setDefaultRenderer(String.class, new
new ColorRenderer());
ColorRenderer());

This
This means
means that
that all
all columns
columns that
that contains
contains objects
objects of
of type
type String
String uses
uses this
this renderer
renderer and
and thus
thus
the
the first
first two
two columns.
columns.

SORTING
SORTING ROWS
ROWS
A
A JTable
JTable supports
supports sorting
sorting of
of rows
rows by
by clicking
clicking the
the mouse
mouse onon aa column.
column. Clicking
Clicking onceonce sorted
sorted
rows of the column’s values in ascending order, and click it again to sort
rows of the column’s values in ascending order, and click it again to sort in descending in descending
order.
order. The
The example
example Demo07
Demo07 demonstrates
demonstrates how how itit works.
works. The
The data
data model
model isis the
the same
same as
as in
in
the
the above
above examples,
examples, and
and the
the only
only thing
thing that
that must
must happen
happen isis that
that you
you have
have to to specify
specify that
that
it must be possible when the table is created:
it must be possible when the table is created:

private
private JTable
JTable createTable()
createTable()
{{
JTable
JTable table
table == new
new JTable(new
JTable(new DemoDataModel());
DemoDataModel());
table.setAutoCreateRowSorter(true);
table.setAutoCreateRowSorter(true);
return
return table;
table;
}}

FILTERS
FILTERS
FILTERS
This example
This example
This shows
example shows
shows howhow to
how to assign
assign aaa filter.
to assign filter. The
filter. The data
The data model
data model is
model is again
is again the
again the same
the same with
with 999 rows,
same with rows,
rows,
but
but ififif you
but you enter
you enter something
enter something
something in in the
in the input
the input field
input field below
field below the
below the table,
the table, only
table, only the
only the rows
the rows where
rows where the
where the title
the title
title
starts
starts with
starts with what
with what is entered
what isis entered are
entered are shown.
are shown. Below
shown. Below I has
Below II has entered
has entered a large
entered aa large I:
large I:I:

76
76
76
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS The
thecomponent
ComponentJTable
JtaBle

The
Thecode
codeisisasasfollows:
follows:

public class Demo08 extends JDialog


{
private JTextField filterText;
private TableRowSorter<DemoDataModel> sorter;

public Demo08()
{
super(null, "Demo08", JDialog.ModalityType.APPLICATION_MODAL);
setSize(750, 300);
this.setLocationRelativeTo(null);
setLayout(new BorderLayout());
add(new JScrollPane(createTable()));
add(createBottom(), BorderLayout.SOUTH);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}

private JTable createTable()


{
DemoDataModel model = new DemoDataModel();
sorter = new TableRowSorter(model);
JTable table = new JTable(model);
table.setRowSorter(sorter);
return table;
}

private JPanel createBottom()


{
JPanel panel = new JPanel(new BorderLayout(20, 0));
panel.add(new JLabel("Enter filter"), BorderLayout.WEST);
panel.add(filterText = new JTextField());
filterText.getDocument().addDocumentListener(new Filter());
return panel;
}

private void newFilter()


{
RowFilter<DemoDataModel, Object> filter = null;
try
{
filter = RowFilter.regexFilter(filterText.getText(), 1);
}
catch (java.util.regex.PatternSyntaxException ex)
{

7777
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

return;
}
sorter.setRowFilter(filter);
}

class Filter implements DocumentListener


{
public void changedUpdate(DocumentEvent e)
{
newFilter();
}

public void insertUpdate(DocumentEvent e)


{
newFilter();
}

public void removeUpdate(DocumentEvent e)


{
newFilter();
}
}
}

www.job.oticon.dk

78
78
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS The
thecomponent
ComponentJTable
JtaBle
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

The
The first thing you should notice isis that there are defined two instance variables, the first
The first
first thing
thing you
you should
should notice
notice is that
that there
there are
are defined
defined two
two instance
instance variables,
variables, thethe first
first
refers
refers to
to the
the input
input field,
field, while
while the
the other
other has
has the
the type
type TableRowSorter
TableRowSorter and
and is
is for
for the
the used
used
refers to the input field, while the other has the type TableRowSorter and is for the used
data
data model (that is DemoDataModel ). In the constructor isis nothing new, but the method
data model
model (that
(that is
is DemoDataModel
DemoDataModel ). ). In
In the
the constructor
constructor is nothing
nothing new,
new, but
but the
the method
method
createTable()
createTable() creates
creates the
thesorter
sorterobject
object and
and attached
attached it
it to
tothe
the table.
table.The
The method
method createBottom()
createBottom()
createTable() creates the sorter object and attached it to the table. The method createBottom()
creates
creates the input field, and associates the filter to the field the following statement:
creates the
the input
input field,
field, and
and associates
associates the
the filter
filter to
to the
the field
field the
the following
following statement:
statement:

filterText.getDocument().addDocumentListener(new Filter());
filterText.getDocument().addDocumentListener(new Filter());

where
where Filter
Filter isis
where Filter an
is an inner
an inner class
inner class that
class that implements
that implements
implements an an interface
an interface called
interface called DocumentListener.
called DocumentListener.
DocumentListener. This This
This
interface
interface defines
interface defines three
defines three methods
three methods
methods thatthat are
that are executed
are executed when
executed when
when thethe content
the content
content of of the
of the input
the input field
field isis
input field is
changed,
changed,
changed,and and therefore
andtherefore if
thereforeififthe the user
theuser enters
userenters
entersor or deletes
ordeletes anything.
deletesanything.
anything.In In
Inallall three
allthree cases,
threecases, the
cases,the methods
themethods
methods
called
called newFilter(),
newFilter(), and
and it
it isis the
the method
method it
it is
is all
all about.
about. It
It creates
creates aa filter
filter as
as aa regular
regular
called newFilter(), and it is the method it is all about. It creates a filter as a regular expression, expression,
expression,
and
and note
andnote especially
noteespecially
especiallythatthat
thatbyby
byan an index
anindex indicating
indexindicating which
indicatingwhich column
whichcolumn
columnthe the filter
thefilter must
filtermust apply
mustapply
applyto to
to–––inin
in
this
this case,
this case, index
case, index 1
index 11 and and thus
and thus the
thus the title
the title column.
title column. Finally
column. Finally the
Finally the sorter
the sorter object
sorter object is used
object isis used
used to to the
to the filter
the filter
filter
the
the table
the table rows.
table rows.
rows.

PRINT
PRINTAA
PRINT JTABLE
AJTABLE
JTABLE
The
The next
The next example
next example Demo09
Demo09 isis
example Demo09 simple
is simple and
simple and shows
and shows the
shows the same
the same table
table asas
same table above,
as above, but
above, but the
but the example
the example
example
demonstrates
demonstrates how
demonstrates how
how toto print
to print the
print the table
the table
table ofof the
of the printer,
the printer, and
printer, and it could
and itit could hardly
could hardly be
hardly be simpler.
be simpler. The
simpler. The
The
window
window
windowhashas a Print
hasaaPrint button,
Printbutton, and
button,and
andallall that
allthat is needed
thatisisneeded is done
neededisisdone
doneinin the
inthe event
theevent handler
eventhandler for
handlerfor this
forthis button:
thisbutton:
button:

private
private void
void print(ActionEvent
print(ActionEvent e)
e)
{
{
MessageFormat
MessageFormat header
header =
= new
new MessageFormat("Side
MessageFormat("Side {0,
{0, number,
number, integer}");
integer}");
try
try
{
{
table.print(JTable.PrintMode.NORMAL,
table.print(JTable.PrintMode.NORMAL, header,
header, null);
null);
}
}
catch
catch (java.awt.print.PrinterException ex)
(java.awt.print.PrinterException ex)
{
{
JOptionPane.showMessageDialog(this, ex.getMessage());
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
}
}

79
79
79
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable

SYNCHRONIZING TWO TABLES

The next example shows a JTable and JList, and both using the the same data model, but
this time a different data model, there is a list of Danish kings:

Both components thus uses the same data model, and the most important thing about the
model is that there are so many rows, that you needs to scroll the table. The one component
shows only one of the model’s columns, while the second shows all columns. The example
should show that if you click on a row in one of the two components they both scrolls, so
the row that is selected appears at the top (se below).

The data model is called Kings and is relatively complex. It is defined as a class derived
from DefaultListModel, but really it should be an AbstractTableModel (see examples in front).
However, it is not necessary, but it is sufficient to implement the interface TableModel (what
AbstractTableModel do). In return, the class Kings must implement all methods defined by
TableModel. This is possible by defining an object of the type KingsModel that is an inner
class that inherits AbstractTableModel, and the class Kings may then delegates the methods
of the class KingsModel. You are encouraged to study the in principle simple, but a little
unusual implementation of the data model.

80
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable

In the past four years we have drilled

81,000 km
That’s more than twice around the world.

Who are we?


We are the world’s leading oilfield services company. Working
globally—often in remote and challenging locations—we invent,
design, engineer, manufacture, apply, and maintain technology
to help customers find and produce oil and gas safely.

Who are we looking for?


We offer countless opportunities in the following domains:
n Engineering, Research, and Operations
n Geoscience and Petrotechnical
n Commercial and Business

If you are a self-motivated graduate looking for a dynamic career,


apply to join our team. What will you be?

careers.slb.com

81
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS The
thecomponent
ComponentJTable
JtaBle

Then
Thenthere
thereisisthe
thecode
codeofofthe
theuser
userinterface:
interface:

public class Demo10 extends JDialog


{
private Font font = new Font("Liberation Serif", Font.PLAIN, 16);
private Kings dataModel = new Kings();
private JList list;
private JTable table;
private ListSelectionModel listSelectionModel;

public Demo10()
{
super(null, "Demo10", JDialog.ModalityType.APPLICATION_MODAL);
setSize(600, 400);
this.setLocationRelativeTo(null);
setLayout(new BorderLayout());
add(createList(), BorderLayout.WEST);
add(new JScrollPane(createTable()));
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}

private JPanel createList()


{
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel(dataModel.getColumnName(0), JLabel.CENTER);
label.setPreferredSize(new Dimension(0, 32));
label.setBorder(new LineBorder(Color.LIGHT_GRAY));
label.setFont(font);
panel.add(label, BorderLayout.NORTH);
list = new JList(dataModel);
list.setFont(font);
list.setCellRenderer(new DefaultListCellRenderer()
{
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean selected, boolean focus)
{
King king = (King)value;
Component component = super.getListCellRendererComponent(
list, king.getName(), index, selected, focus);
component.setPreferredSize(new Dimension(150, 25));
return component;
}
});
listSelectionModel = list.getSelectionModel();
listSelectionModel.addListSelectionListener(new ListSelectionHandler());
panel.add(new JScrollPane(list));
return panel;
}

8282
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

private JTable createTable()


{
table = new JTable(dataModel);
table.setSelectionModel(listSelectionModel);
JTableHeader header = table.getTableHeader();
header.setPreferredSize(new Dimension(0, 32));
table.setFont(font);
table.setRowHeight(25);
return table;
}

class ListSelectionHandler implements ListSelectionListener


{
public void valueChanged(ListSelectionEvent e)
{
int index = e.getSource() ==
table ? table.getSelectedRow() : list.getSelectedIndex();
list.ensureIndexIsVisible(index);
Rectangle rect = table.getCellRect(index, 0, true);
table.scrollRectToVisible(rect);
table.scrollRectToVisible(list.getCellBounds(
index, dataModel.getSize() – 1));
list.scrollRectToVisible(list.getCellBounds(index, dataModel.getSize() – 1));
}
}
}

The components
The components are are placed
placed in in the
the window
window in in the
the constructor.
constructor. The The JList
JList component
component
isis created
created in in the
the method
method createList(),
createList(), where
where itit isis placed
placed in
in aa panel
panel withwith aa label
label above.
above.
Next the
Next the list
list isis assigned
assigned aa new
new CellRenderer
CellRenderer object
object created
created on
on the
the basis
basis of
of an
an anonymous
anonymous
class that
class that inherits
inherits DefaultListCellRenderer,
DefaultListCellRenderer, and and does
does not
not much,
much, but but overrides
overrides the
the method
method
getListCellRendererComponent().The
getListCellRendererComponent(). Thelist’s
list’sdata
datamodel
modelisiskings,
kings,and
andthe themethod
methodhas hastotoensure
ensure
that only
that only thethe name
name isis shown
shown and and thethe cell
cell has
has aa preferred
preferred size
size to
to fit
fit the
the height
height ofof the
the rows
rows
inin the
the JTable
JTable component.
component. Next Next the the variable
variable listSelectionModel
listSelectionModel isis setset to
to refer
refer to
to list
list box’s
box’s
SelectionModel, and
SelectionModel, and toto this
this isis attached
attached an an event
event handler
handler ofof the
the type
type ListSelectionHandler
ListSelectionHandler
(that isis an
(that an inner
inner class).
class).

Then there
Then there isis the
the method
method createTabel(),
createTabel(), and and here
here you you mainly
mainly notice
notice how how toto defines
defines thethe
height of
height of the
the table’s
table’s header
header and
and rows.
rows. Finally,
Finally, note
note thatthat the
the table
table isis assigned
assigned toto the
the same
same
SelectionModelasasthe
SelectionModel thelist
listbox.
box.This
Thismeans
meansthat thatititisisthe
thesame
sameevent
eventhandler
handlerthatthatisisexecuted
executed
ifif you
you click
click on
on one
one ofof the
the two
two components,
components, and and itit isis this
this handler
handler thatthat scrolls
scrolls the
the two
two
components so
components so that
that the
the element
element that
that isis clicked,
clicked, isis atat the
the top.
top.

83
83
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS The
the component
Component JTable
JtaBle

JTABLE
JTABLE AND
AND DATABASE
DATABASE TABLES
TABLES
The
The example
example Demo11
Demo11 showsshows how how toto display
display the
the content
content of of aa database
database table
table with
with aa JTable.
JTable.
The
The example
example opens
opens the
the window
window below.
below. The
The window
window shows
shows aa JTable
JTable with
with the
the content
content of of the
the
table
table zipcode.
zipcode. AtAt the
the bottom
bottom of of the
the window,
window, there
there isis aa button
button and
and twotwo input
input fields.
fields. The
The
input
input fields
fields act
act as
as filters
filters for
for the
the two
two columns,
columns, while
while button
button clears
clears the
the fields.
fields. Regarding
Regarding the the
definition
definition of the table and window and including the filters there is nothing new, so it isis
of the table and window and including the filters there is nothing new, so it
the
the data
data model
model you
you need
need to to be
be interested,
interested, and
and here
here isis actually
actually not
not very
very new:
new:

package jtabledemo;

import java.sql.*;
import java.util.*;
import javax.swing.table.*;

public class Zipcodes extends AbstractTableModel


{
private List<Zipcode> list = new ArrayList();

public Zipcodes()
{
try (Connection conn = DriverManager.getConnection(

Linköping University
– Innovative, well ranked, European
Interested in Engineering and its various
branches? Kick-start your career with an
English-taught master’s degree.

liu.se/master

Click here!

84
84
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

"jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234"))


{
Statement stmt = conn.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM zipcode");
while(res.next())
list.add(new Zipcode(res.getString("code"), res.getString("city")));
}
catch (SQLException ex)
{
System.out.println(ex);
}
}

public int getColumnCount()


{
return 2;
}

public int getRowCount()


{
return list.size();
}

public String getColumnName(int col)


{
return col == 0 ? "Code" : "City";
}

public Object getValueAt(int row, int col)


{
return col == 0 ? list.get(row).getCode() : list.get(row).getCity();
}

public Class getColumnClass(int c)


{
return String.class;
}

public boolean isCellEditable(int row, int col)


{
return false;
}

85

85
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

public void setValueAt(Object value, int row, int col)


{
if (col == 0)
list.get(row).setCode((String)value);
else
list.get(row).setCity((String)value);
fireTableCellUpdated(row, col);
}
}

The only
The only place
place where
where isis something
something new
new isis in
in the
the constructor,
constructor, and
and itit isis nothing
nothing more
more than
than
the initial
the initial examples
examples in
in this
this book
book has
has illustrated,
illustrated, that
that isis how
how to
to read
read aa database
database table.
table.

The conclusion
The conclusion isis that
that itit isis quite
quite simple
simple to
to display
display the
the content
content of
of aa database
database table
table using
using aa
JTable –– you
JTable you just
just need
need toto initialize
initialize the
the data
data model
model with
with the
the content
content ofof the
the database
database table.
table.

86
86
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS The
the component
Component JTable
JtaBle

BIG
BIG TABLES
TABLES
The
The last
last example
example will
will opens
opens the
the following
following window:
window:

The
The window
window shows
shows aa JTable,
JTable, and
and there
there are
are 10000
10000 rows
rows and
and 200
200 columns
columns and and thus
thus 22 million
million
cells.
cells. The
The example
example will
will primarily
primarily show
show that
that aa JTabel
JTabel can
can have
have manymany cells,
cells, and
and itit isis still
still
effective.
effective. You can also edit the individual cells except the last row and the last column. In
You can also edit the individual cells except the last row and the last column. In
the
the cells
cells you
you can
can enter
enter numbers,
numbers, and and the
the bottom
bottom row
row shows
shows allall the
the time
time the
the column
column sum, sum,
while
while the
the last
last column
column shows
shows all
all the
the time
time the
the row
row sum.
sum.

The
The data
data model
model isis simple
simple and
and adds
adds nothing
nothing new:
new:

class SpreadsheetModel extends AbstractTableModel


{
private Object[][] data;

public SpreadsheetModel(int rows, int cols)


{
data = new Object[rows + 1][cols + 1];
}

87
87
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

public int getColumnCount()


{
return data[0].length;
}

public int getRowCount()


{
return data.length;
}

public Object getValueAt(int row, int col)


{
return data[row][col];
}

public Class getColumnClass(int c)


{
return Double.class;
}


678'<)25<2850$67(5©6'(*5((

&KDOPHUV8QLYHUVLW\RI7HFKQRORJ\FRQGXFWVUHVHDUFKDQGHGXFDWLRQLQHQJLQHHU
LQJDQGQDWXUDOVFLHQFHVDUFKLWHFWXUHWHFKQRORJ\UHODWHGPDWKHPDWLFDOVFLHQFHV
DQGQDXWLFDOVFLHQFHV%HKLQGDOOWKDW&KDOPHUVDFFRPSOLVKHVWKHDLPSHUVLVWV
IRUFRQWULEXWLQJWRDVXVWDLQDEOHIXWXUH¤ERWKQDWLRQDOO\DQGJOREDOO\
9LVLWXVRQ&KDOPHUVVHRU1H[W6WRS&KDOPHUVRQIDFHERRN

88
88
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable
JAVA 6: JDBC AND DATABASE APPLICATIONS the Component JtaBle

public boolean isCellEditable(int row, int col)


{
return col < data[0].length – 1 && row < data.length – 1;
}

public void setValueAt(Object value, int row, int col)


{
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}

You should
You should notice
notice how
how it
it is
is defined
defined that
that to
to the
the last
last row
row and
and last
last column
column must
must not
not be
be edited,
edited,
while all
while all other
other cells
cells must.
must. You
You should
should also
also notice
notice that
that each
each column
column contains
contains objects
objects of
of the
the
type Double
type Double and
and thus
thus numbers.
numbers.

Then there
Then there is is the
the dialog
dialog box,
box, where
where there
there is
is more
more to
to note.
note. II will
will not
not show
show thethe code
code here,
here,
partly it
partly it fills
fills aa lot,
lot, and
and secondly,
secondly, it
it is
is mainly
mainly something
something as
as discussed
discussed earlier
earlier in
in this
this chapter,
chapter,
so I’ll
so I’ll just
just mention
mention aa fewfew things
things that
that you
you need
need to
to notice
notice when
when you
you study
study the
the code:
code:

1. There
1. There are
are two
two defined
defined constants
constants which
which define
define the
the table
table size.
size. You
You could
could try
try to
to
experiment and
experiment and change
change these
these constants.
constants.
2. How
2. How to to define
define aa RowHeader
RowHeader that
that isis encapsulated
encapsulated inin aa JViewPort
JViewPort that
that is
is inserted
inserted in
in
the JScrollPane
the JScrollPane that
that contains
contains the
the JTable
JTable component.
component.
3. An
3. An inner
inner class
class CellEditorHandler
CellEditorHandler that that is
is event
event handler
handler for
for editing
editing aa cell
cell
4. A
4. A class
class DoubleEditor,
DoubleEditor, that
that is
is aa CellEditor.
CellEditor.
5. A
5. A class
class RowNumberHeader,
RowNumberHeader, that that is
is aa JTable
JTable and
and defines
defines the
the type
type of
of table’s
table’s RowHeader.
RowHeader.

89

89
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable

PROBLEM 2
You must write a program that you can call the Denmark, which opens the following window:

The window shows two JTable components located in a JSplitPane. The table on the left
shows all rows in the table zipcode while the table on the right shows all rows in the table
municipality, but only the municipality’s name and the name of the region. During the two
tables, there are four input fields used for filters, to the above column. The two buttons at
the top is used to clear the filters.

If you double-click on a line in the table with the zip codes, you should get the following
window:

that for the zip code displays the names of the municipalities that uses this zip code. If
you double-click a line in the table with municipalities, you must get a window as shown
below, where you partly receive the municipality’s area and number of inhabitants, and
partly a table with the zip codes that this municipality uses. This table (the table with local
zip codes) must be a JTable component.

90
JAVA 6: JDBC AND DATABASE APPLICATIONS The component JTable

Welcome to
our world
of teaching!
Innovation, flat hierarchies
and open-minded professors

Study in Sweden -
close collaboration
with future employers
Mälardalen university collaborates with
many employers such as ABB, volvo and
Ericsson

TAKE THE
debajyoti nag
Sweden, and particularly
MDH, has a very impres-
sive reputation in the field

RIGHT TRACK
of Embedded Systems Re-
search, and the course
design is very close to the
industry requirements.
He’ll tell you all about it and
answer your questions at
mdustudent.com
give your career a headstart at mälardalen university
www.mdh.se

91
JAVA
JAVA
6: 6:
JDBC
JDBC
AND
AND
DATABASE
DATABASE
APPLICATIONS
APPLICATIONS Files
FIles
inIn
databases
dataBases

8
8 FILES
FILESIN
INDATABASES
DATABASES
It Itis isalso
alsopossible
possibletotosave
savefiles
filesinindatabases,
databases,forforexample
examplePDF PDFdocuments,
documents,XML XMLdocuments
documents
ororimages.
images.It Ithas
haslimited
limiteduse,
use,butbutwith
withweb webapplications
applicationsone onesometimes
sometimesseesseesexamples
exampleswhere
where
images
imagesarearestored
storedinindatabases,
databases,and andif ifthese
thesearearesmall
smallfiles,
files,there
theremay
mayalso
alsobebesituations
situationswhere
where
it itis isok.
ok.InInthis
thissection
sectionI Iwill
willshow
showhow howtotododothat.
that.

A Acolumn
columnthat thatmust
mustcontain
containa afile
filemust
mustbebeofofthe
thetype
typeTEXTTEXT(for(fordocuments)
documents)ororBLOBBLOB
(binary
(binaryfiles
fileslike
likeimages).
images).The
Thefollowing
followingscript
script(CreateFileDb.sql )
(CreateFileDb.sql )creates
createsa adatabase
databasewith
with
two
twotables,
tables,oneonetable
tabletotodocuments,
documents,while whilethe
theother
otheris isforforimages:
images:

use sys;
drop database if exists filedb;
create database filedb;
use filedb;

create table documents (


filename varchar(100), # the documents name
description varchar(100), # a short description
content longtext, # the documents content
primary key(filename)
);

create table pictures (


filename varchar(100), # the filename
description varchar(100), # a short description
content longblob, # picture data
primary key(filename)
);

Thefollowing
The followingprogram
programis iscalled
calledUploadDocs
UploadDocsand
andopens
opensthe
thefollowing
followingwindow:
window:

92 92
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Files
FIles in
In databases
dataBases

When
When you you click
click the
the Upload
Upload button,
button, you
you get
get aa standard
standard dialog
dialog where
where you you can
can browse
browse file
file
systems
systems andand find
find the
the file
file that
that you
you want
want toto store
store in
in the
the database.
database. IfIf you you double-click
double-click at at aa
line
line in
in the
the table,
table, you
you get
get aa similar
similar dialog
dialog box
box where
where youyou can
can browse
browse to to aa folder,
folder, and
and the
the
program
program mustmust then
then save
save the
the content
content of
of the
the database
database rowrow as
as aa file
file in
in that
that folder.
folder.

The
The event
event handler
handler for
for the
the button
button is:
is:

private void upload(ActionEvent e)


{
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(System.getProperty("user.home")));
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
String description = JOptionPane.showInputDialog(this, "Description:",
"Enter text", JOptionPane.PLAIN_MESSAGE);
streamFile(file, description);
}
}

private void streamFile(File file, String description)


{
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/filedb?useSSL=false", "pa", "Volmer_1234"))
{
long length = file.length();
FileInputStream in = new FileInputStream(file);
PreparedStatement stmt =
conn.prepareStatement("INSERT INTO documents VALUES(?, ?, ?)");
stmt.setString(1, file.getName());
if (description == null) stmt.setNull(2, java.sql.Types.VARCHAR);
else stmt.setString(2, description);
stmt.setAsciiStream(3, in, length);
stmt.executeUpdate();
model.add(new Document(file.getName(), description));
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(this, file.getAbsolutePath() +
" could not be streamed to the database\n" + ex,
"Error message", JOptionPane.ERROR_MESSAGE);
}
}

93
93
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Files
FIles in
In databases
dataBases

The
The event
event handler
handler creates
creates aa JFileChooser
JFileChooser object
object and and open
open thethe dialog
dialog box
box so
so that
that you
you are
are placed
placed
in
in the
the user’s
user’s home
home directory.
directory. IfIf the
the user
user selects
selects aa file,
file, the
the user
user should
should enter
enter aa description
description
of
of the
the document
document (the(the file).
file). Then
Then the
the method
method streamFile()
streamFile() isis called,
called, that
that streams
streams thethe file
file to
to
the database. This method opens a FileInputStream to the file and
the database. This method opens a FileInputStream to the file and then a connection to then a connection to
the
the database
database and
and initialize
initialize aa PreparedStatement.
PreparedStatement. The The only
only thing
thing toto note
note isis the
the fact
fact that
that the
the
column
column 33 (the
(the third
third parameter
parameter in in stmt 
stmt)) isis initialized
initialized with
with the
the method
method setAsciiStream()
setAsciiStream() withwith
the
the InputStream
InputStream asas aa parameter.
parameter.

You
You should
should note
note that
that the
the program
program does does not
not try
try to
to validate
validate the
the file,
file, and
and in
in fact
fact the
the program
program
can
can upload
upload any
any file
file and
and store
store itit in
in the
the database
database –– even
even aa picture.
picture.

IfIf you
you double-click
double-click aa line
line in
in the
the table,
table, the
the following
following event
event handler
handler isis performed:
performed:

class MouseHandler extends MouseAdapter


{
public void mousePressed(MouseEvent e)
{
try
{
if (e.getClickCount() == 2)
{

LIFE SCIENCE IN UMEÅ, SWEDEN


– YOUR CHOICE!
• 32 000 students • world class research • top class teachers
• modern campus • ranked nr 1 in Sweden by international students
• study in English

– Bachelor’s programme in Life Science


– Master’s programme in Chemistry
– Master’s programme in Molecular Biology

Download
brochure
here!

94
94
JAVA 6: JDBC AND DATABASE APPLICATIONS Files in databases
JAVA 6: JDBC AND DATABASE APPLICATIONS FIles In dataBases

int row = table.getSelectedRow();


Document doc = model.getDocument((Integer)table.getValueAt(row, 0));
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(System.getProperty("user.home")));
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fc.showSaveDialog(MainView.this) == JFileChooser.APPROVE_OPTION)
streamFile(fc.getSelectedFile(), doc);
}
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(MainView.this,
"could not be streamed trom the database\n" + ex,
"Error message", JOptionPane.ERROR_MESSAGE);
}
}
}

Thereisisnot
There notsosomuch
muchnew,
new,but
butthe
theuser
userwill
willbebeable
abletotoselect
selectthe
thedirectory
directorytotowhere
wherethe
thefile
file
shouldbe
should besaved.
saved.IfIfaadirectory
directoryisisselected
selectedthe
themethod
methodstreamFile()
streamFile()isiscalled,
called,which
whichcreates
creates
thefile,
the file,and
andretrieves
retrievesthe
thecontent
contentfrom
fromthe
thedatabase:
database:

private void streamFile(File file, Document doc) throws Exception


{
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/filedb?useSSL=false", "pa", "Volmer_1234"))
{
PreparedStatement stmt =
conn.prepareStatement("SELECT content FROM documents WHERE filename = ?");
stmt.setString(1, doc.getFilename());
ResultSet res = stmt.executeQuery();
if (res.next())
{
InputStream stream = res.getAsciiStream (1);
BufferedInputStream in = new BufferedInputStream(stream);
String filename = file.getAbsolutePath() + "/" + doc.getFilename();
BufferedOutputStream out =
new BufferedOutputStream(new FileOutputStream(filename));
int c;
while ((c = in.read ()) != -1) out.write(c);
out.close();
}
}
}

95
95
JAVA 6: JDBC AND DATABASE APPLICATIONS Files in databases

Again, there is not much new to explain. The method creates a PreparedStatement with one
parameter, which is value to the primary key. The SELECT statement defines only a single
column, as the column of file’s content. If the row is found the content in the column is
referenced to with the method getAsciiStream(), which is an InputStream. It is encapsulated in
a BufferedInputStream (of performance reasons), and then is created a BufferedOutputStream
that represents the file to which the database content must be streamed.

In the example, the data streaming to and from the database is performed with an AsciiStream
that treat data as ASCII bytes encoded as ISO-Latin-1. There are other options:

-- UnicodeStream, where the data is treated as 16-bits unicode


-- BinaryStream, where the data is treated as raw bytes

and the difference is, what services these types provides.

EXERCISE 5
You must write a program similar to the above, and the program should open a window,
as shown below:

The program must upload pictures to the filedb database and store the pictures in the
table pictures, but in contrast to the above program it must use a BinaryStream. It should
only be possible to upload jpg, gif and png files. If you double-click a line in the table,
the corresponding file should in the same manner as in the above program be copied to a
directory in the file system.

The table's right column consists of check boxes. If you click on the Remove button, the
images selected must be removed from the database.

96
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS ddl commands
DDL Commands

9 DDL COMMANDS
9
IfIf you
you have
have to
to create
create aa database
database and
and including
including itsits tables,
tables, you
you will
will in
in practice
practice usually
usually write
write
aa SQL
SQL script.
script. When
When aa script
script consists
consists of
of SQL
SQL commands,
commands, these these commands
commands can can ofof course
course
also be
also be performed
performed using
using JDBC,
JDBC, andand II close
close this
this explanation
explanation of of JDBC
JDBC with
with anan example
example that
that
shows how
shows how to to create
create aa database
database and
and aa table
table in
in the
the database.
database. Actually,
Actually, it’s
it’s just
just to,
to, and
and the
the
following test
following test method
method creates
creates aa database:
database:

private static void test12()


{
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306?useSSL=false", "pa", "Volmer_1234"))
{
Statement stmt = conn.createStatement();
stmt.executeUpdate("CREATE DATABASE contacts");
}
catch(SQLException ex)
{
System.out.println(ex);
}
}

Scholarships

Open your mind to


new opportunities
With 31,000 students, Linnaeus University is
one of the larger universities in Sweden. We
are a modern university, known for our strong
international profile. Every year more than Bachelor programmes in
1,600 international students from all over the Business & Economics | Computer Science/IT |
world choose to enjoy the friendly atmosphere Design | Mathematics
and active student life at Linnaeus University.
Master programmes in
Welcome to join us! Business & Economics | Behavioural Sciences | Computer
Science/IT | Cultural Studies & Social Sciences | Design |
Mathematics | Natural Sciences | Technology & Engineering
Summer Academy courses

97
97
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS DDL
ddlcommands
Commands

The
Thenext
nextmethod
methodcreates
createsaatable
tableininthis
thisdatabase:
database:

private static void test13()


{
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306?useSSL=false", "pa", "Volmer_1234"))
{
Statement stmt = conn.createStatement();
stmt.execute("use contacts");
stmt.executeUpdate("CREATE TABLE persons (
id int auto_increment not null primary key,
name varchar(50) not null, phone varchar(20), email varchar(50) )");
}
catch(SQLException ex)
{
System.out.println(ex);
}
}

and
andthen
thenititshould
shouldbe
beclear
clearthat
thatall
allDDL
DDLcommands
commandsimmediately
immediatelycan
canbe
beexecutable
executablefrom
from
aaJava
Javaprogram
program––ififyou
youhave
havethe
therights
rightstotoperform
performthe
thecommands.
commands.

98
98
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

10 FINAL EXAMPLES
I will finish this book about JDBC and databases with two examples of database applications.
The two examples are similar and are classic examples of database applications and in addition
to the size in which the first is a small program, while the other is slightly larger, so the
difference is that the first use an existing database, while the latter shows the development of
a database program right from the start, which also includes the design and implementation
of the database.

10.1 WORLD
In the exercises and problems in this book you have expanded the database padata with
three tables

-- world
-- country
-- currency

The task now is to write a program that can maintain these tables, and thus a program
where you can search the tables, as well as edit and delete data. The program must have a
graphical user interface.

THE REQUIREMENTS

Before I will address the development, the requirements must be defined and therefore
which functions the program must be able to perform.

1. The program should open a window (the main view) with two tables, one table
provides an overview of all countries, while the second shows an overview of
all currencies.
2. It should be possible to create a new country.
3. It should be possible to edit the information about a country.
4. It must be possible to delete a country.
5. It must be possible to create a new currency.
6. It should be possible to edit information about a currency and here especially the
exchange rate.
7. It must be possible to delete a currency, if there is no country that uses this currency.
8. It should be possible to update exchange rates with data from a CSV file.

99
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Final
FInal examples
examples

It
It has
has been
been decided
decided that
that you
you should
should not
not be
be able
able to
to maintain
maintain the
the table
table world
world with
with information
information
about
about the
the world’s
world’s continents.
continents.

Except
Except for
for the
the first
first and
and the
the last
last function
function the
the requires
requires does
does not
not needs
needs further
further explanation.
explanation.
With
With regard
regard to
to the
the main
main view
view II will
will define
define it
it aa prototype.
prototype. As
As regards
regards the
the last
last function,
function, aa
CSV
CSV file
file must
must consist
consist of
of lines
lines of
of the
the form
form

code;rate[;name]

and there must at least be a currency code and a currency exchange rate om each line. If
the currency is available i the database, the currency’s rate is updated. Otherwise, a new
currency should be created, if the line contains a name for the currency. The function should
show lines that contains errors and can not update the table.

YOUR WORK AT TOMTOM WILL


BE TOUCHED BY MILLIONS.
AROUND THE WORLD. EVERYDAY.
Join us now on www.TomTom.jobs
follow us on

#ACHIEVEMORE

100
100
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

THE PROTOTYPE

The prototype is a program called World, which opens the following window:

The program should show the design of the main view. The window shows two JTable
components in a JSplitPane and the tables shows an overview for respectively currencies
and countries. Search is implemented with filters below each table, and the Clear buttons
are used to remove the filters. The two buttons above the currency table are used for

-- import of currency exchange rates from a CSV file


-- add a new currency to the table (and the database)

The button above the countries table is used to add a new country, while the combo
box contains a list of all continnents in the world and offers the opportunity to filter the
countries table by continent.

To edit and possible delete either a currency or a country is decided that you have to
double click the current object in one of the two tables, and then you get a dialog box
that displays the object’s data.

101
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

To
Towrite
writethe
theprototype
prototypeI Ihave
havecreated
createda anew
newproject
projectWorld
WorldininNetBeans,
NetBeans,and
andbesides
besidesthe
the
main-class,
main-class,are
areadded
addedthe
thefollowing
followingclasses
classes(files)
(files)

--- MainView,
MainView,thatthatisisthe
theabove
abovewindow
window
--- Currencies,
Currencies,that
thatisisa adata
datamodel
modelfor
forthe
thecurrency
currencytable
table
--- Countries,
Countries,that
thatisisa adata
datamodel
modelfor
forthe
thecountry
countrytable
table

The
Thelast
lasttwo
twoare
aretrivial,
trivial,but
butthey
theyare
arenecessary
necessaryfor
forthe
theprototype
prototypecan
cancreate
createthe
thetwo
twoJTable
JTable
components.
components.As Asananexample
exampleisisshown
shownthe
theone
onebelow:
below:

package world;

import javax.swing.table.*;

public class Countries extends AbstractTableModel


{
public int getColumnCount()
{
return 2;
}

public int getRowCount()


{
return 0;
}

public String getColumnName(int col)


{
return col == 0 ? "Code" : "Name";
}

public Object getValueAt(int row, int col)


{
return null;
}

public boolean isCellEditable(int row, int col)


{
return false;
}
}

Afterthe
After theprototype
prototypeisisfinished,
finished,I’ve
I’vecreated
createda acopy
copyofofthe
theproject,
project,which
whichI Ihave
havecalled
called
World0.I Iwill
World0. willnow
nowcontinue
continuetotowork
workon onthe
theproject,
project,but
butwith
withthe
thecopy
copyI Ican
canalways
alwaysreturn
return
totothe
theprototype.
prototype.

102
102
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

THE DATA MODEL


As a next step I have written some model classes, and thus the classes to represent the
program’s data.

There’s added three very simple model classes, representing respectively a continent, a
country and currency:

-- Continent
-- Country
-- Currency

The classes are directly modeling the rows in the corresponding database tables, however,
the class Currency extends with a list containing Country objects for the countries using
this currency.

There are also defined a collection for each of the above types:

-- Continents
-- Countries
-- Currencies

103
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

each of which includes an object for each row in the corresponding database table. Here the
first of the classes is trivial, while the other two are reprogrammings of the corresponding
classes from the prototype. The two classes are thus at the same time model for the program’s
JTable components.

The total model is represented by the class DataModel, which is a simple class that is
made up of an object by each of the above three collections. The program’s model can be
illustrated as follows:

The three collections must be initialized, which is done by reading the corresponding database
tables. To this end, it is written a class Repository, which only has static methods, including
among others, methods that creates the three collection classes. The class Repository also has
update methods for the tables currency and country, and that means that everything that
has to do with the database is collected in this class. If the application must use a different
database, it means that only this class has to be changed. The class Repository is a relatively
complex class, as everything concerning the database and SQL are gathered here, and thus
everything that is introduced in this book.

THE USER INTERFACE

The program’s user interface consists besides MainView of

-- CurrencyView which is a dialog box for maintenance of currencies


-- CountryView which is a dialog box for maintaining the countries

Furthermore, there is a secondary dialog box called ErrorView and is used to display a list
of errors with the import of exchange rates. Below is the MainView, which is the same view
as in the prototype, but this time initialized with data:

104
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

For each view (except ErrorView) there is attached a controller. The goal is that the controller
class should validate the user input and choices, and it is also, where appropriate the controller
classes that calls the methods in the class Repository to update the model. The controller
classes for the two dialog boxes for maintaining respectively currencies and countries works
in principle the same. Below is the dialog for maintaining currency:

105
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

It is the same dialog that is used regardless of whether to create a new currency, or to edit
an existing currency. In this case, there is double clicked EUR, in the main window.

Similarly is below shown the dialog box for the maintenance of countries and where there
are double clicked on US:

106
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

By thus associating a controller for a dialog you achieves two things:

1. everything regarding algorithms and business logic is moved into a separate class
2. the code of dialog box becomes simpler and easier to understand

Now one should not at any price attach a controller class for a dialog/window. A controller
class must contain something interesting for it to makes sense.

IMPORT AF CSV FILE

The last feature that is missing is updating the exchange rates from a CSV file. This includes
being able to open the file, parse it and use the result of the pasing to update the database
table currency. With regards to browse the file, it is an activity that belongs in an event
handler in the MainView. When the file is selected, it is sent to the controller class for
MainView, which then parses the file and validate the individual lines. On the basis of the
legal lines it creates Currency objects, which are sent to a method in the class Repository,
which then updates the database.

10.2 MYWINES
The following project is to write a classic database application. This means that you must
create a database and write a program that can maintain this database. The program is an
ordinary PC application, that should maintain information about a private wine cellar,
which is not entirely realistic. Should such a program be written in practice, you would
probably write a web application. It should be ignored, and the purpose of the project is
to test most of the substance that is treated in this book.

Compared with the programs that I have shown in this and the previous books, it is a
relatively large program, and it is also a program that can be used in practice if one has
a wine cellar and feel a need to register his wine consumption. The program consists of
many classes (about 80), and there are more than 25 windows (dialogs). Now it’s all not
as violent as it sounds. Most of the dialog boxes are simple, and the same goes for the
corresponding classes. All dialog boxes are implemented in the same manner with a view
class that implements everything concerning the user interface, and then one or two model
classes. There will always be a model class, which models the object which the dialog box
maintains, and in the case where the dialog box has to display a collection of objects
(rows in a database table), a JTabel is used in the user interface, and the dialog box has
also assigned a data model for a JTable. In addition to model classes most dialog boxes
also have a controller class that validates the user input and possible calls methods in the
application’s repository to update the database. You should therefore note that many dialog
boxes are implemented in the same way that makes it easier to understand the program
and thus maintain the code.

107
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

When you have to write a program which, that as in this example, will consist of many
dialog boxes (the program has many features) which are similar and almost works the same
way, you can then try to reduce the code and the number of dialog boxes by parameter
control the dialog boxes and apply them to multiple functions depending on the parameters
that are transferred to the constructors. If you do that, you get less code and fewer classes
and thus, in principle, a program that is easier to maintain, but however more complex
classes, which can be difficult to understand, because you have dialog boxes that perform
several functions. Conversely, a dialog box for every function mean that the number of
classes becomes very large, which in turn may mean that you have to change in many places
for maintains the program. It is a choice, and in the current solution I have tried to some
extent to parameter control dialogs without letting it go beyond clarity.

You are encouraged to spend the time reading the following description of how the program
is designed and also to study the final result and including primary the program’s code and
to test the program.

THE TASK

Many private wine lovers has a substantially wine storage – perhaps several hundred bottles
or more. It requires control, including to ensure that the wine is not too old, but also for
the sake of historical data with information about prices, ratings, etc. These historical data
are vital when buying the same wine again, but also to learn from experience and in general
as documentation of purchase and consumption. There is thus not only a need to keep
track of the current stock, but at least as much a need to store information about wines
that are drunk and removed from the wine cellar.

The wines are acquired from different Danish suppliers – including grocery stores, but there
may also be stock entries either in the form of direct import (that is from holidays or trips
to wine countries) or gifts. The wines are purchased at greatly varying prices, and especially
in connection with gifts, the price can be 0 (or lack of ). It is common in the business, the
granting of large discounts (and, arguably, even unrealistically large similar to that the list
prices is not real). The price, and thus the discount granted is often determined by whether
you buy single bottles or boxes (of 6 or 12 bottles).

The task is to write a program called MyWines that should be used to manage a private wine
cellar. The program should be written in accordance with the following requirements/wishes.

108
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

In general, it should be possible to record the following information about a wine:

Information on the supplier (where the wine is purchased or obtained):

The supplier’s phone number

-- The supplier’s name (company name or other)


-- The supplier’s address
-- The supplier’s zip code
-- The supplier’s city
-- The supplier’s email address

Which supplier information that actual should be recorded may vary, because a wine can
be a gift or be imported from abroad.

WE WILL TURN YOUR CV


INTO AN OPPORTUNITY
OF A LIFETIME

Do you like cars? Would you like to be a part of a successful brand?


Send us your CV on
As a constructer at ŠKODA AUTO you will put great things in motion. Things that will
www.employerforlife.com
ease everyday lives of people all around Send us your CV. We will give it an entirely
new new dimension.

109
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

Information about the wine (that is facts about the product):

-- The wine’s name


-- The producer’s name
-- The wine’s type (white, red, rosé, sparkling, dessert, port)
-- The country where the wine is produced
-- The country’s code
-- Wine district (for example Alsace, Barolo etc.)
-- The grapes used for the production of the wine and in what quantities
-- Classification if there is a classification (for example Chianti Classico Riserva DOCG)
-- The wine’s vintage
-- Alcohol percent
-- Size of the bootle/packing (in cl)

Information about the purchase:

-- The date when the wine is purchased


-- Expiry date (date when the wine latest should be drunk)
-- The wine’s price without discount
-- Discount price
-- The number of bottles purchased
-- Quality (D = daily wine, H = house wine, Q = quality wine, C = cellar wine,
X = cult wine)

The stock levels:

-- Stock level (the current number of bottles)


-- Revised quality (D, H, Q, C, X)
-- Rating – an assessment consists of a date and a character from 0 to 100
-- A description of the wine as a text

Every time there is used a bottle from the store, you have to register, which wine it is, how
many bottles are taking and when.

110
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

For both the supplier and the wine itself one can not expect that all the information is
present, and the same goes for how long the wine can be saved, discount and classification
when a new wine must be added to the store, and in general you should be aware that
sometimes you only have the knowledge that you can get from the label on the bottle.

The program should basically have the following features:

1. Register/create new wines (purchase)


2. Updates (consumption from the store and classifications)
3. Search functions

Because the work of records information about wines can be comprehensive (there may be
many details), you should aim for a solution where you have to enter as little as possible,
and where it is easy to get the data available, which is already in the system. On the whole,
you should priority that the program is easy to use and it is important that the program is
robust and react sensibly by improper operation.

The program must have a search function where one can easily search wines from several
criteria. You should aim for enhanced flexibility when searching, but conversely, the function
should not be too complex. In connection with the search for wines, one should get:

-- an overview of the total wine purchases within a given period and if necessary with
the possibility of demarcation on country or by other criteria
-- an overview of the total consumption within a given period and if necessary with
the possibility of demarcation on country or by other criteria
-- an overview of a wine’s rating assessments over time (points)

It is also a desire that the program has a feature where one quickly can get a list of the
wines that have reached the expiration date, and possibly has exceeded the expiration date,
but also wines that should be drunk within the next time.

111
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

DATABASE DESIGN

I will start the development with design and implentation of the database. If I look at the
above description of the task, the database should contain infomation about suppliers, and
the analysis of the description results in two tables (se below). Basically, it is an address book,
and here you will usually place the zip code and the city name in a table for zip codes, and
then let code be a foreign key in the table supplier. Sometimes one can illustrate database
tables with a figure as below, here indicates that there are two tables, and what columns
these tables must have. If the name of a column is underlined it means that the column
is a primary key. Which columns there should be, comes from the description of the task,
but in practice the software developer through an analysis must contact the person who
has proposed the task to clarify uncertainties, but also exactly to define the data types to
be used. In this case, information about the supplier has been expanded with a new value,
where it is possible to register a description of the supplier. On a figure as below the arrow
shows, that the table supplier must have a foreign key to the table zipcode.

Develop the tools we need for Life Science


Masters Degree in Bioinformatics

Bioinformatics is the
exciting field where biology,
computer science, and
mathematics meet.

We solve problems from


biology and medicine using
methods and tools from
computer science and
mathematics.

Read more about this and our other international masters degree programmes at www.uu.se/master

112
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

The
The primary
primary database
database table
table isis aa table
table wine,
wine, which
which should
should contain
contain information
information about
about aa
particular
particularwine,
wine,and
andthus
thusaawine
winetotobe beincluded
includedininthe
thecellar.
cellar.This
Thistable
tablewould
wouldhave
haveamong
among
others the following columns:
others the following columns:

wineid int # surrogate key


name varchar(50), # the wine's name
year int, # the wine's production year
time int, # expiration time in years
percent decimal(5,1), # alcohol percent
store varchar(100), # storing on barrel / tank / bottle
amount int, # current amount
text text, # description of the wine

andhere
and hereititisisalso
alsoagreed
agreedthat
thatititshould
shouldbe
bepossible
possibletotoregister
registeraadescription
descriptionofofaawine.
wine.AA
winehas
wine hastotobe beidentified
identifiedby
byaasurrogate
surrogatekey,
key,and
andititisisagreed
agreedthat
thattwo
twowines
winesare
areconsidered
considered
different,ififthey
different, theydo donot
nothave
havethe
thesame
sameproduction
productionyear.
year.Furthermore,
Furthermore,for
foreach
eachwine
wineititmust
must
bepossible
be possibletotodefine
define

--- supplier
supplier
--- packing(bottle,
packing (bottle,bib,
bib,other)
other)
--- producer
producer
--- productioncountry
production country
--- district
district
--- classification
classification
--- winetype
wine type
--- winecategory
wine category

113
113
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

Here are suppliers already described and the table wine must have a foreign key to the
supplier. The 7 other informations is in principle text, but it has been decided to register
the individual information in their own table. The argument is partly that several wines
must be registered with the same value, and second, that it can be difficult to ensure that
the same text is spelled the same way each time, and finally you have for packing and
district to register an addional information which is respectively the packing’s volume and
the district’s country. For the type of wine and wine categories the description of the task
defines a natural primary key (one letter), but for the other 5 I has to choose a surrogate
key. The design should therefore be extended with 7 other but simple tables (these tables are
sometimes called dimension tables) and the table wine must have additional 8 foreign keys.

There is also a need for a table to purchases:

where a purchase is identified by the primary key of the table wine as well as a date. Based
on the analysis it has been decided that the same wine can not be purchased twice the same
day. Should the same wine could be purchased several times on the same day, it would be
necessary to expand the table with a surrogate key.

Similarly, there must be a table with information on consumption of wines:

Here however, it is decided to use a surrogate key corresponding to the possibility of


consuming the same wine several times on the same day.

Finally, there must be a table to record the user’s ratings by the 100 points scale:

114
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

and here it is again assumed that the individual wine has only one registration per day (only
one rating for a wine the same day).

After these considerations, the design of the database is illustrated as shown below.

Along with the project is a script called Wine.sql that creates the database. I will not show
the script here, but in addition to the database – called cellar – the script initializes the
four tables:

-- zipcode
-- winetype
-- category
-- pack

Copenhagen
Master of Excellence cultural studies
Copenhagen Master of Excellence are
two-year master degrees taught in English
at one of Europe’s leading universities religious studies

Come to Copenhagen - and aspire!

Apply now at science


www.come.ku.dk

115
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

PROGRAM ARCHITECTURE

The program should in principle be able to maintain the above database, and to that purpose
the program must use some windows and dialog boxes, and the program will consist of
many files (types). As a start, I have therefore created a project MyWines and created the
following packages:

116
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

-- mywines is the default package created by NetBeans, and should just contain the
class with the main() method
-- mywines.ctrls should contain all controller classes to dialog boxes
-- mywines.models should be used for model classes, which is essentially a model class
for every database table
-- mywines.repositories that should contain classes with the SQL code, and then the
code that extracts data from tables and update the tabels
-- mywines.tables that belongs to the user interface layer and consists at classes thatt
act as data models for JTable components
-- mywines.views that shouls contain dialog boxes

In addition is added a reference to my class library PaLib, when I will use tools from
this library.

THE MODEL LAYER

I am now ready to start on the development of the program and I will begin with the model
layer and writes the first model classes, when a model class should modeling a row in a
database table. So far, I will concentrate on the table wine and the tables which it refers,
and I will write the following model classes:

-- Zipcode
-- Supplier
-- Producer
-- Category
-- Classification
-- Winetyper
-- Grape
-- Country
-- District
-- Packing
-- Wine

117
JAVA
JAVA 6:
6: JDBC AND DATABASE
JDBC AND DATABASE APPLICATIONS
APPLICATIONS Final
FInal examples
examples

Except
Except the last they
the last they are
are all
all simple
simple and
and vary
vary only
onlyininterms
termsofofthe
thefields
fieldsthey
theycontains.
contains.AsAsanan
example is shown the
the class
class District
District that
that isis modeling
modelingthe thetable
tabledistrct:
distrct:

package mywines.models;

public class District


{
public static final int NAME = 50;
private final int id;
private String name;
private String code;

public District(int id, String name, String code)


{
this.id = id;
this.name = name;
this.code = code;
}

public int getId()


{
return id;
}

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

118

118
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

public String getName()


{
return name;
}

public String getCode()


{
return code;
}

public void setName(String name)


{
this.name = name;
}

public void setCode(String code)


{
this.code = code;
}

@Override
public boolean equals(Object obj)
{
if (obj == null) return false;
if (getClass() == obj.getClass()) return id == ((District)obj).id;
return false;
}

@Override
public int hashCode()
{
return id;
}

@Override
public String toString()
{
return name;
}
}

The
Theclass
classisissimple
simplesince
sinceititonly
onlycontains
containsget
getand
andset
setmethods
methodsforforthe
theclass’s
class’svariables,
variables,but
but
note that the class overrides equals() so that two objects are equal, if the
note that the class overrides equals() so that two objects are equal, if the corresponding corresponding
rows
rowsininthethedatabase
databasehave
havethethesame
sameprimary
primarykey.
key.Also
Alsonote
notethat
thatthere
thereareareinitially
initiallydefined
defined
aapublic
publicconstant
constantNAME,NAME,that thatindicates
indicateshow
howmanymanycharacters
charactersare
arereserved
reservedininthethedatabase
database
for the column name (in the database the type is VARCHAR(50) ).
for the column name (in the database the type is VARCHAR(50) ).

119
119
JAVA6:6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS FInalexamples
examples
JAVA
JAVA JDBC AND DATABASE APPLICATIONS Final
FInal examples

Thedevelopment
The
The developmentofof
development ofa aadatabase
databaseapplication
database applicationwill
application willtypically
will typicallystart
typically starttoto
start towrite
writethat
write thatkind
that kindofof
kind ofmodel
model
model
classes.There
classes.
classes. Theremay
There mayofof
may ofcourse
coursebebe
course bevariations,
variations,but
variations, butbasically
but basicallythey
basically theywill
they willmodel
will modelthe
model thedatabase
the databasetable’s
database table’s
table’s
columns,and
columns,
columns, andoften
and oftenthe
often theclasses
the classeswill
classes willalso
will alsobebe
also beexpanded
expandedlater
expanded laterinin
later inthe
thedevelopment
the developmentprocess.
development process.
process.

Theclass
The
The classwine
class wineisis
wine isbasically
basicallydesigned
basically designedinin
designed inthe
thesame
the sameway,
same way,but
way, butitit
but ittakes
takesup
takes upa aalot
up lotmore,
lot more,asas
more, asthe
thetable
the table
table
winehas
wine
wine hasmany
has manycolumns.
many columns.The
columns. Thebeginning
The beginningofof
beginning ofthe
theclass
the classis:is:
class is:

public class
public class Wine
Wine
{
{
private int
private int id;
id;
private String name;
private String name;
private Integer
private Integer year;
year;
private Integer time;
private Integer time;
private BigDecimal
private BigDecimal pct;
pct;
private String barrel;
private String barrel;
private int
private int units;
units;
private String text;
private String text;
private Packing
private Packing packing;
packing;
private Supplier supplier;
private Supplier supplier;
private Producer
private Producer producer;
producer;
private Country country;
private Country country;
private District
private District district;
district;
private Classification classification;
private Classification classification;
private Category
private Category category;
category;
private Winetype winetype;
private Winetype winetype;
private List<Cuve>
private List<Cuve> cuve;
cuve;
private boolean mark
private boolean mark = = false;
false;

Here
Hereyou
Here youshould
you shouldnote
should notehow
note howthe
how thecolumns
the columnsfor
columns forthe
for theforeign
the foreignkeys
foreign keysare
keys aredefined
are definedasas
defined asa aareference
referencetoto
reference to
anan
anobject
objectofof
object ofthat
thatmodel
that modeltype.
model type.That
type. Thatis,is,
That is,ifif
ifyou,
you,for
you, forexample,
for example,consider
example, considerthe
consider thesupplier,
the supplier,itit
supplier, itisis
isnot
nota aa
not
String
String(for
String (forthe
(for theprimary
the primarykey
primary keyphone),
key phone),but
phone), buta aareference
but referencetoto
reference toa aaSupplier
Supplierobject.
Supplier object.
object.

YouYoushould
You shouldalso
should alsonote
also notethe
note thevariable
the variablecuve,
variable cuve,that
cuve, thatisis
that isa aacollection
collectionwith
collection withobjects
with objectsofof
objects ofthe
thetype
the typeCuve.
type Cuve.
Cuve.
TheThedatabase
The databasehas
database hasa aatable
has tablecuve
table cuvethat
cuve thatisis
that isa aarelation
relationtable
relation tablebetween
table betweenwine
between wineand
wine andgrapes
and grapesand
grapes anddefines
and defines
defines
which
whichgrapes
which grapesare
grapes arepart
are partofof
part ofa aawine.
wine.The
wine. Theclass
The classCuve
class Cuvemodelings
Cuve modelingsthis
modelings thistable,
this table,but
table, butisis
but isexpanded
expandedwith
expanded with
with
a aavariable
variablefor
variable forthe
for thegrape’s
the grape’sname:
grape’s name:
name:

public class
public class Cuve
Cuve
{
{
private int
private int wineid;
wineid;
private int
private int grapeid;
grapeid;
private String name;
private String name;
private Integer
private Integer pct;
pct;
private boolean mark
private boolean mark == false;
false;

120
120
120
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal examples
Final examples

There is also aa variable


There variablemark,
mark,which
whichallows
allowsto to
highlight
highlight(select) objects
(select) in aincollection.
objects The
a collection.
classclass
The winewine
has ahas
corresponding variable.
a corresponding You You
variable. will will
se, how this this
se, how variables are used
variables in the
are used in user
the
interface.
user interface.

THE MAINVIEW
THE MAINVIEW

II will
will then
then write
write the
the program’s
program’s MainView,
MainView, but but first
first II have
have in
in MySQL
MySQL Workbench
Workbench performed
performed
the following
the following script
script that
that creates
creates aa supplier
supplier and
and three
three wines:
wines:

use cellar;

INSERT INTO supplier (phone, name, address, code, email) VALUES


('98921853', 'Supervin', 'Skagensvej 201', '9800', 'info@supervin.dk');
INSERT INTO wine (name, year, phone) VALUES
('Clos Sainte Anne', 2013, '98921853');
INSERT INTO wine (name, year, phone) VALUES
('Chateau Lamartine', 2011, '98921853');
INSERT INTO wine (name, year, phone) VALUES
('Montecore Primitivo', 2015, '98921853');

The script is called Threewines.sql, and the aim is, that the database should contain data,
The script is called Threewines.sql, and the aim is, that the database should contain data,
which can be displayed on the front window.
which can be displayed on the front window.

Trust and responsibility


NNE and Pharmaplan have joined forces to create – You have to be proactive and open-minded as a
NNE Pharmaplan, the world’s leading engineering newcomer and make it clear to your colleagues what
and consultancy company focused entirely on the you are able to cope. The pharmaceutical field is new
pharma and biotech industries. to me. But busy as they are, most of my colleagues
find the time to teach me, and they also trust me.
Inés Aréizaga Esteva (Spain), 25 years old Even though it was a bit hard at first, I can feel over
Education: Chemical Engineer time that I am beginning to be taken seriously and
that my contribution is appreciated.

NNE Pharmaplan is the world’s leading engineering and consultancy company


focused entirely on the pharma and biotech industries. We employ more than
1500 people worldwide and offer global reach and local knowledge along with
our all-encompassing list of services. nnepharmaplan.com

121
121
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

When I start with the main window, it is because I as quickly as possible wants to get a
running program, so the program’s user interface can be presented and finally defined with
the future users.

When the program is executed, it should show the follwing window:

Center is a JTable, that shows an overview over all wines, but later it should show only be
the wines, where the number of bottles in stock are positive. The last column with the check
boxes should be used to select rows, that shows wines to be drunk. The JTextField’s at the
bottom are for filters. If the user double-click on a wine in the table, the program should
open a dialog box with all the details about that wine. The menu has the following functions:

-- The wines properties


1. Maintenance of suppliers
2. Maintenance of producers
3. Maintenance of countries
4. Maintenance of districts
5. Maintenance of classifications
6. Maintenance of grapes
7. Maintenance of wine types
8. Maintenance of wine categories
9. Maintenance of bottles/packings

122
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

--- Other
Otherfunctions
functions
1.
1. AdvancedSearch
Advanced Search
2. Purchase
2. Purchase
3.
3.Consumption
Consumption

To
Towrite
writethe
theclass
classMainiew
MainiewI Ihave
havealso
alsowritten
writtenthe
thefollowing
followingclasses
classes

--- mywines.tables.Wines
mywines.tables.Wines
--- mywines.repositories.DB
mywines.repositories.DB
--- mywines.repositories.Repository
mywines.repositories.Repository

The
Theclass
classWines
Winesisisa asimple
simplemodel
modelclass
classtotoa aJTable,
JTable,and
andcontains
containsnothing
nothingnew.
new.The
Theclass
class
DB
DBshould
shouldrepresents
representsa aconnection
connectiontotoa adatabase
databaseand
andisiswritten
writtenasasa asingleton:
singleton:

package mywines.repositories;

import java.sql.*;

public class DB
{
private static DB instance = null;
private String host = "localhost";
private String port = "3306";
private String data = "cellar";
private String user = "pa";
private String code = "Volmer_1234";

private DB()
{
}

public static DB getInstance()


{
if (instance == null)
{
synchronized (Repository.class)
{
if (instance == null) instance = new DB();
}
}
return instance;
}

123
123
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

public Connection getConnection() throws SQLException


{
return DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s?useSSL=false", host, port, data), user, code);
}
}

Immediatelythe
Immediately theclass
classmakes
makeslittle
littlesense,
sense,since
sinceititmerely
merelyconsists
consistsofofvariables
variablesthat
thatcontains
contains
parametersfor
parameters forthe
thedatabase,
database,but
butthe
theclass
classmust
mustbe beused
usedtotosolve
solvethe
theproblem
problemthat
thatthe
thedatabase
database
parametersare
parameters arehard
hardcoded
codedso
sothey
theycan
canbebelifted
liftedout
outofofthe
theprogram
programtotoaaconfiguration
configurationfile.
file.

The class
The class Repository
Repository isis also
also written
written asas aa singleton,
singleton, and
and so
so far
far itit has
has only
only aa single
single method
method
that can
that can return
return aa Wine
Wine object
object for
for all
all rows
rows inin the
the table
table wine.
wine. However,
However, itit isis the
the program’s
program’s
centralclass,
central class,and
andwill
willincludes
includesall
allmethods
methodsfor fordatabase
databaseoperations.
operations.ItItthusthusbecomes
becomesaavery
very
extensiveclass.
extensive class.Al
AlSQL
SQLisishidden
hiddenaway
awayininthis thisclass.
class.

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

124
124
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

THE DIMENSION TABLES

As a next step I want to write the code for the maintenance the dimension tables, and thus
all functions under the menu The wines properties. All functions works in principle the same
way, and I will as an eksemple look at the Maintenance of wine types. If you click the menu
item, the program opens the following dialog box:

The dialog box shows a JTable with all wine types and such the content of the table winetype,
and at the bottom is defined a filter to the table. The two buttons are used to create a new
wine type and to remove a filter. Double-Clicking on a line in the table, you get a dialog
box where you can edit (and delete) a wine type, for example:

It is the same dialog used if you create a new wine type.

125
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

The menu item The wines properties has 9 functions, and for each of the 9 functions the
following should happens:

1. The class Repository must be extended with 4 new methods, a method that returns
a list of objects corresponding to the content of the database table, a method that
creates a new row in the database, a method that updates an existing row and a
method that deletes an existing row.
2. A class that is a data model for the JTable component.
3. A class that is the dialog box with the JTable component.
4. A class that is a controller for the dialog box to edit an object.
5. A class that is the last dialog box.

When the menu has 9 functions it means that the program may be expanded with 36 new
classes like the class Repositoty must be expanded with 36 new methods. It sounds like a lot
and it is, but conversely note, that there is also talk about the program code to maintain
9 database tables, and finally you should note that the classes are generally simple, and the
same applies to the methods in the class Repository.

You should also note that the implementation is a form of a pattern for a program to
maintain a database table, where you have a dialog box with a JTable and filter that displays
the content of the database table, and where you can open a dialog to add or edit a row
in the table. I like to do the job in this way, because it is clear when the table is changed,
but there are other ways, and here it is particularly important to note that one can edit
the contents of a JTable directly.

THE WINE TABLE

Maintenance of the table wine follow the same pattern. That is, the MainView has a button
to create a new wine, and if you double-click on a line in the table, you can edit the wine.
In both cases the same dialog box is used, and in principle it means as above

-- the class Repository must be expanded with 3 new features (the function that returns
all wines have already been implemented)
-- to write a controller for the dialog
-- the dialog box itself must be written

The difference is that this time it is a very complex dialog that has a number of other
functions. If you double-click a wine in the main window, the result could be the window
as shown below.

126
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

The dialog box has to the left input fields for the information, that can be entered, while
the right side is combo boxes to select a value from a dimension table. Everything should
be self-explanatory except for the two JTable components for the grapes. The bottom
shows a table with all the grapes in the database with an associated filter. The top is to the
grapes used in this wine. If you in the lower JTable choose one or more grapes by placing a
checkmark in the check box and click the Add button, these grapes are added to the upper
JTable and therefore grapes that are part of the wine. In the upper JTable you can similarly
set a checkmark in one or more check boxes, and if you clicks on Remove, the grapes are
removed from the wine. The top JTable also has a column that is to the grape’s part in this
wine if it is composed of several grapes. This column is edited by directly entering a value
(in percent).

At the top of the window there are 6 buttons. They are used to create an object of that
kind and thus has the same function as the functions that can be selected from the menu.
The meaning of these shortcuts is, that if you are about to create a new wine (or edit an
existing wine), and you as such discovers that the wine is from a district which was not
been created, that you can instantly create the district. These 6 functions are using the same
dialog boxes that are created earlier for maintenance of dimension tables.

Sharp Minds - Bright Ideas!


Employees at FOSS Analytical A/S are living proof of the company value - First - using The Family owned FOSS group is
new inventions to make dedicated solutions for our customers. With sharp minds and the world leader as supplier of
cross functional teamwork, we constantly strive to develop new unique products - dedicated, high-tech analytical
Would you like to join our team? solutions which measure and
control the quality and produc-
FOSS works diligently with innovation and development as basis for its growth. It is tion of agricultural, food, phar-
reflected in the fact that more than 200 of the 1200 employees in FOSS work with Re- maceutical and chemical produ-
search & Development in Scandinavia and USA. Engineers at FOSS work in production, cts. Main activities are initiated
development and marketing, within a wide range of different fields, i.e. Chemistry, from Denmark, Sweden and USA
Electronics, Mechanics, Software, Optics, Microbiology, Chemometrics. with headquarters domiciled in
Hillerød, DK. The products are
We offer marketed globally by 23 sales
A challenging job in an international and innovative company that is leading in its field. You will get the companies and an extensive net
opportunity to work with the most advanced technology together with highly skilled colleagues. of distributors. In line with
the corevalue to be ‘First’, the
Read more about FOSS at www.foss.dk - or go directly to our student site www.foss.dk/sharpminds where
company intends to expand
you can learn more about your possibilities of working together with us on projects, your thesis etc.
its market position.

Dedicated Analytical Solutions


FOSS
Slangerupgade 69
3400 Hillerød
Tel. +45 70103370

www.foss.dk

127
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

At the bottom of the window are a further 8 buttons, and the meaning of the buttons OK
and Cancel gives itself. The 6 other can only be activated if you are editing a wine, but not
when you create a new wine. There function are explained below.

The button Remove is used til remove a wine. The function also removes all other information
related to this wine.

The button Copy is used to create a new wine with virtually the same data, but where the
fields year, drunk and units is null. The reason is that the same wine in another year is
considered as another wine, and then a new year can be created without to enter all the
information again.

128
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

The button Point opens a dialog box called PointView as shown below. The function is used
to assign a rating to this wine. The dialog box inserts today (that can be changed), and
you should enter the point as a number between 0 and 100. A rating can not directly be
changed, but if you double-click on a rating, you can remove it, and you can create all the
ratings you like, but you can only create one rating for the same date. If you enter a rating
for an existing date, the old value is overriden.

You should note, that dialog box has a JTable, and as so need a data model for the table
(in the package mywines.tables). The same applies to the two JTable components above for
the grapes. It means that every JTable add a class, and for the three mentioned here it is
Ratings, Cuves and Grapes. PointView is a simple dialog box, but should update the database,
and for that is assigned a controller with the name PointCtrl.

The buton Purchase opens the following dialog box:

129
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

that is used to enter information about a purchase of a wine, and that is the price and
number og units. The dialog box is called PurchaseView and the controller PurchaseCtrl.

The button Consume opens a dialog box to enten information about a consumption:

The dialog box is called ConsumptionView and the controller CunsumptionCtrl.

130
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

The last button Units opens a dialog box that shows what has happened with the store for
this wine, that is alle purchases and consumptions:

The dialog box shows primarily a JTable with a filter. If you double-click on a row in the
table you are allowed to delete the actual purchase or consumption. The dialog box is called
UnitView, and the data model to the JTable is called Units. The dialog also has a controller
called UnitCtrl.

As described above, maintenance of wines is a function which extends the program with
several new classes. Furthermore the function results in an extension of the class Repository
with many new methods, and here you should special note, that several of these methods
are implemented as database transactions.

131
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

THE SEARCH FUNCTIONS

Then there is the three functions in the last menu. The three functions are very similar and
opens dialogs with almost the same design. The first opens a dialog box as shown below
and is used to search for wines based on several criteria. The window shows an example
where there has been searched on all French wines. If a field is empty (has not been selected
a search criteria), it is ignored in the search. If you enter a value in the fields Name and
Description it means that a row in the database to match must contain the value in the actual
column. For a criteria where you can enter two values, it means a from and to value, and if
you only enter one value if means either from or to. If you select a value in a combo box
a row in the wine table must have that value in the actual column (in the example belov
a row must have the value FR for country.

If you double-click a row in the table, the program opens til dialog box WineView for that
wine, and you kan maintain the wine.

132
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

The two other search functions opens corresponding dialogs, and I will not show these
dialogs here. The difference is that for both dialogs you also can choose a period as search
criteria, and the JTable component has some other columns. Moreover, both dialogs shows
some totals at the bottom. The first dialog is called PurchasesView and displays a list of all
the purchases that matches the search criteria.

The Wake
the only emission we want to leave behind

.QYURGGF'PIKPGU/GFKWOURGGF'PIKPGU6WTDQEJCTIGTU2TQRGNNGTU2TQRWNUKQP2CEMCIGU2TKOG5GTX

6JGFGUKIPQHGEQHTKGPFN[OCTKPGRQYGTCPFRTQRWNUKQPUQNWVKQPUKUETWEKCNHQT/#0&KGUGN6WTDQ
2QYGTEQORGVGPEKGUCTGQHHGTGFYKVJVJGYQTNFoUNCTIGUVGPIKPGRTQITCOOGsJCXKPIQWVRWVUURCPPKPI
HTQOVQM9RGTGPIKPG)GVWRHTQPV
(KPFQWVOQTGCVYYYOCPFKGUGNVWTDQEQO

133
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

If you double-click a row in the table, you get the above dialog box showing all ratings
for the wine. The last function works similar, but shows an overview of consumptions that
matches the search criteria. If you here double-click a row, you get the following dialog:

The dialog box displays consumption by dates and again an overview of all ratings.

The three functions in turn results in a number of new classes, and I will not mention
them here, but the three dialogs with search criteria are extensive but similar each other
and therefore everything they have in common are moved to a base class:

There should be written some code to implement these three functions, but there is not
much new compared to what already is mentioned. The most complex is to create the SQL
expression to be used, partly because there are JOIN operations on many tables, and partly
because the WHERE part depends on the search criteria selected. Everything happens in
class Repository, and you are encouraged to study the code and the many details.

134
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

THE
THELAST
LASTTHINGS
THINGS
Back
Backthere
thereare
aretwo
twothings:
things:

1.
1.moving
movingthe
thedatabase
databaseparameters
parametersfrom
fromthe
theprogram
programcode
codetotoaaconfiguration
configurationfile
file
2. write an installation script
2. write an installation script

Regarding
Regardingthe
thefirst
firstproblem,
problem,I Iwill
willuse
usethe
thefollowing
followingconfiguration
configurationfile
filecalled
calledmywines.config
mywines.config

host:localhost
port:3306
data:cellar
user:pa
code:Volmer_1234

Next, the class DB is changed:

package mywines.repositories;

import java.io.*;
import javax.swing.*;
import java.sql.*;

public class DB
{
private static String path = System.getProperty("user.home") + "/";
private static DB instance = null;
private String host = "";
private String port = "";
private String data = "";
private String user = "";
private String code = "";

private DB()
{
try (BufferedReader reader =
new BufferedReader(new FileReader(path + "mywines.config")))
{
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
String[] item = line.trim().split(":");
if (item.length == 2)
{
String key = item[0].trim();
if (key.equals("host")) host = item[1].trim();

135
135
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

else if (key.equals("port")) port = item[1].trim();


else if (key.equals("data")) data = item[1].trim();
else if (key.equals("user")) user = item[1].trim();
else if (key.equals("code")) code = item[1].trim();
}
}
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(null,
"The program can not connect to the database.",
"ErrorMessage", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}

public static DB getInstance()


{
if (instance == null)
{
synchronized (Repository.class)
{
if (instance == null) instance = new DB();
}

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57


136

136
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

}
return instance;
}

public static void setPath(String pathname)


{
if (!pathname.endsWith("/")) pathname += "/";
path = pathname;
}

public Connection getConnection() throws SQLException


{
return DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s?useSSL=false", host, port, data), user, code);
}
}

The database
The database parameters
parameters areare now
now blank,
blank, and
and inin return,
return, the
the private
private constructor
constructor isis changed
changed
to read
to read the
the configuration
configuration file
file and
and initializes
initializes the
the parameters.
parameters. IsIs itit not
not possible,
possible, and
and here
here you
you
must remember
must remember that that the
the constructor
constructor isis performed
performed the the first
first time
time the
the method
method getInstance()
getInstance() isis
called, itit shows
called, shows aa message
message box,
box, and
and the
the program
program terminates.
terminates.

By default
By default thethe constructor
constructor assumes
assumes that
that the
the configuration
configuration file
file exists
exists in
in the
the user’s
user’s home
home
directory. ItIt does
directory. does of
of course
course not
not have
have toto be
be the
the case,
case, and
and therefore
therefore the
the class
class has
has aa static
static
method that
method that cancan be
be used
used to
to define
define the
the directory
directory that
that contains
contains the
the configuration
configuration file.
file.

After this
After this class
class with
with main()
main() method
method isis changed:
changed:

package mywines;

public class MyWines


{
public static void main(String[] args)
{
if (args != null && args.length > 0) mywines.repositories.DB.setPath(args[0]);
javax.swing.SwingUtilities.invokeLater(() -> new mywines.views.MainView());
}
}

IfIf main()
main() has has an
an argument
argument on on the
the command
command line,
line, use
use the
the first
first argument
argument as as aa directory
directory for
for
the configuration
the configuration file.
file. You
You should
should also
also note
note that
that the
the MainView
MainView isis opened
opened in in aa different
different way.
way.
ItIt isis explained
explained inin the
the book
book Java
Java 88 and
and can
can be
be ignored
ignored in in this
this place,
place, but
but itit isis the
the right
right way
way
to start
to start the
the program.
program.

137
137
JAVA
JAVA6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

Then
Then there’s
there’s the
the final
final challenge
challenge with
with an
an installation
installation script.
script. The
The following
following files
files should
should be
be
installed:
installed:

MyWines.jar
MyWines.jar
lib/PaLib.jar
lib/PaLib.jar
mywines.png
mywines.png
mywines.config
mywines.config

The
The script
script isis called
called mywines.sh.
mywines.sh. II will
will not
not show
show the
the script
script here,
here, because
because in
in principle
principle itit works
works
the
the same
same way,
way, as as II have
have shown
shown before.
before.

To
To run
run the
the program,
program, thethe database
database mustmust be be created
created and
and therefore
therefore the
the database
database script
script mustmust be
be
executed
executed before
before the
the program
program cancan bebe used.
used. To
To distribute
distribute the
the program,
program, II packs
packs itit all
all together
together
in
in aa tar
tar file.
file. First
First II copied
copied all
all files
files to
to the
the directory
directory data/mywines
data/mywines in in my
my home
home directry:
directry:

[pa@localhost ~]$ ls -lR data/mywines


data/mywines:
totalt 488
drwxrwxr-x. 2 pa pa 4096 12 jan 21:38 lib
-rwxrwxrwx. 1 pa pa 63 12 jan 21:13 mywines.config
-rw-rw-r--. 1 pa pa 456246 12 jan 23:06 MyWines.jar
-rwxrwxrwx. 1 pa pa 20297 12 jan 21:37 mywines.png
-rwxrwxrwx. 1 pa pa 988 13 jan 17:30 mywines.sh
-rw-rw-r--. 1 pa pa 6886 7 jan 12:09 Wine.sql

data/mywines/lib:
totalt 44
-rw-rw-r--. 1 pa pa 43682 12 jan 21:38 PaLib.jar

Next, I created the tar file:

[pa@localhost ~]$ tar -tvf mywines.tar


drwxr-xr-x pa/pa 0 2017-01-13 17:49 data/mywines/
drwxrwxr-x pa/pa 0 2017-01-12 21:38 data/mywines/lib/
-rw-rw-r-- pa/pa 43682 2017-01-12 21:38 data/mywines/lib/PaLib.jar
-rwxrwxrwx pa/pa 988 2017-01-13 17:30 data/mywines/mywines.sh
-rwxrwxrwx pa/pa 63 2017-01-12 21:13 data/mywines/mywines.config
-rwxrwxrwx pa/pa 20297 2017-01-12 21:37 data/mywines/mywines.png
-rw-rw-r-- pa/pa 456246 2017-01-12 23:06 data/mywines/MyWines.jar
-rw-rw-r-- pa/pa 6886 2017-01-07 12:09 data/mywines/Wine.sql

138
138
JAVA
JAVA6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

and
and the
the result
result isis that
that my
my home
home directory
directory contains
contains the
the file
file mywines.tar,
mywines.tar, and
and hence
hence thethe file
file
which
which can
can bebe distributed
distributed toto users
users of
of the
the program.
program. Here
Here thethe user
user must
must extract
extract the
the file:
file:

$ tar -xvf mywines.tar

IfIf the
the user
user isis in
in the
the directory
directory where
where the
the files
files are
are extracted
extracted and
and perform
perform the
the following:
following:

1.
1. edit
edit the
the configuration
configuration file
file
2.
2. opens
opens MySQL
MySQL Workbench
Workbench and and performed
performed the
the script
script Wine.sql
Wine.sql
3. performs the installation script
3. performs the installation script

and
and then
then the
the program
program should
should be
be running.
running.

But
But there
there may
may be
be aa problem
problem with
with Java
Java and
and the
the JDBC
JDBC driver.
driver. IfIf appropriate,
appropriate, you
you can
can find
find
the solution in appendix
the solution in appendix A.A.

Technical training on
WHAT you need, WHEN you need it
At IDC Technologies we can tailor our technical and engineering
training workshops to suit your needs. We have extensive OIL & GAS
experience in training technical and engineering staff and ENGINEERING
have trained people in organisations such as General
ELECTRONICS
Motors, Shell, Siemens, BHP and Honeywell to name a few.
Our onsite training is cost effective, convenient and completely AUTOMATION &
customisable to the technical and engineering areas you want PROCESS CONTROL
covered. Our workshops are all comprehensive hands-on learning
experiences with ample time given to practical sessions and MECHANICAL
demonstrations. We communicate well to ensure that workshop content ENGINEERING
and timing match the knowledge, skills, and abilities of the participants.
INDUSTRIAL
We run onsite training all year round and hold the workshops on DATA COMMS
your premises or a venue of your choice for your convenience.
ELECTRICAL
For a no obligation proposal, contact us today POWER
at training@idc-online.com or visit our website
for more information: www.idc-online.com/onsite/

Phone: +61 8 9321 1702


Email: training@idc-online.com
Website: www.idc-online.com

139
139
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Final
FInal examples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

APPENDIX
APPENDIX A:
A: INSTALL
INSTALL MYSQL
MYSQL
The
The following
The following isis
following is aaa brief
brief description
brief description of
description of how
of how to
how to install
to install the
install the database
the database server
database server MySQL,
server MySQL, and
MySQL, and as
and as
as
mentioned
mentioned at
mentioned at the
at the beginning
the beginning of
beginning of this
of this book,
this book, you
book, you must
you must install
must install three
install three products:
three products:
products:

1.
1. the
1. the database
the database server
database server
server
2. a client
2. aa client
2. tool
client tool for
for managing
tool for managing and
managing and maintaining
and maintaining databases
maintaining databases
databases
3.
3. aaa JDBC
3. JDBC driver
JDBC driver
driver

Generally
Generally the
Generally the three
the three products
three products are
products are installed
are installed without
installed without major
without major problems,
major problems, and
problems, and the
and the following
the following shows
following shows
shows
how I installed
how II installed
how the
installed the products
the products on
products on a regular
on aa regular PC
regular PC running
PC running Fedora
running Fedora 23.
Fedora 23.
23.

THE
THE DATABASE
THE DATABASE SERVER
DATABASE SERVER
SERVER
The
The server
The server can
server can be
can be downloaded
be downloaded from
downloaded from the
from the page
the page
page

http://dev.mysql.com/downloads/mysql/
http://dev.mysql.com/downloads/mysql/

Here,
Here, you
Here, you should
you should select
should select platform
select platform (for
platform (for example
(for example Fedora),
example Fedora), and
Fedora), and when
and when
when youyou then
you then click
then click Download
click Download
Download
you will
you
you will be
will be asked
be asked to
asked to log
to log in,
log in, and
in, and isis
and is itit
it the
the first
the first time
first time you
time you download
you download MySQL,
download MySQL, you
MySQL, you must
you must create
must create
create
an user
an
an user logon.
user logon. After
logon. After you
After you have
you have logged
have logged in,
logged in, select
in, select the
select the product,
the product, and
product, and III have
and have chosen:
have chosen:
chosen:

Fedora 23
Fedora 23 (Architecture
(Architecture Independent),
Independent), RPM
RPM Package
Package

Then
Then you
Then you get
you get the
get the usual
the usual window
usual window for
window for Download
Download /// Installation,
for Download Installation, which
Installation, which in
which in this
in this case
case isis
this case is aaa rpm
rpm
rpm
package:
package:
package:

140
140
140
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Final
FInal examples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

II have
have chosen
chosen Software
Software installation,
installation, so
so the
the product
product will
will be
be installed
installed in
in my
my software
software repository.
repository.
IItIthave
does chosen
does not
not takeSoftware
take many installation,
many moments,
moments, and so the
and then product
then the will
the product be installed
product must
must be in my
be installed, software
installed, which repository.
which means
means that
that
It
thedoes
the not takepackages
individual
individual many moments,
packages (there areand
(there are then
66 in
in all)the
all) product
must
must be must be installed,
be downloaded
downloaded and which means
and installed.
installed. that
ItIt happens
happens
the
quite
quiteindividual
by
by itself packages
itself with
with the (there areSoftware:
the program
program 6 in all) must be downloaded and installed. It happens
Software:
quite by itself with the program Software:

Once installation
Once installation isis complete,
complete, you
you can
can start
start the
the server
server with
with the
the following
following command:
command:
Once installation is complete, you can start the server with the following command:
sudo service mysqld start
sudo service mysqld start
and then the server will automatically start every time you start the machine. You can test
and
that then
and then the
the server
server
the server will
will automatically
is runningautomatically start
start every
with the following every time
time you
command: you start
start the
the machine.
machine. You
You can
can test
test
that the server is running with the following command:
that the server is running with the following command:
sudo service mysqld status
sudo service mysqld status

141
141

141
JAVA
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
examples

After
After that
After that MySQL
that MySQL in
MySQL in principle
in principle isis
principle is been
been installed
been installed and
installed and running.
and running. What
running. What isis
What is lacking
lacking isis
lacking is aaa kind
kind
kind
of
of configuration which is done using a script. After MySQL is installed, there is created aaa
of configuration
configuration which
which is
is done
done using
using a
a script.
script. After
After MySQL
MySQL is
is installed,
installed, there
there is
is created
created
database
database administrator
database administrator called
administrator called root
called root and
root and isis
and is the
the only
the only database
only database user.
database user. As
user. As part
As part of
part of the
of the installation
the installation
installation
the
the script
the script has
script has auto-generated
has auto-generated a password
auto-generated aa password
password forfor this
for this user
this user that
user that is
that is stored
is stored
stored inin the
in the file
the file /var/log/mysqld.
file /var/log/mysqld.
/var/log/mysqld.
log.
log. You
You can
can for
for example
example find
find this
this password
password with
with
log. You can for example find this password with the command the
the command
command

sudo
sudo grep
grep 'temporary
'temporary password'
password' /var/log/mysqld.log
/var/log/mysqld.log

Once
Once you
Once you have
you have found
have found this
found this password,
this password, you
password, you must
you must run
run aaa script:
must run script:
script:

mysql_secure_installation
mysql_secure_installation

Here
Here you
you will
will be
be prompted
prompted to to enter
enter the
the password,
password, and
and then
then select
select aa new
new password
password for
for root.
root.
Here
The you will be prompted to enter the password, and then select a new password for root.
The script
script will
will then
then ask
ask you
you about
about different
different things,
things, all
all of
of which
which have
have to
to do
do with
with security
security
The
(and script
also awill then
little ask you
clean-up), about
and you different
just things,
answer Yes all
to of
all. which have to do with security
(and also a little clean-up), and you just answer Yes to all.
(and also a little clean-up), and you just answer Yes to all.
After
After the
the script
script is
is completed,
completed, the
the database
database is
is installed
installed and
and ready
ready for
for use.
use.
After the script is completed, the database is installed and ready for use.

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

142
142
142
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

THE CLIENT TOOL

Together with the database server is installed a command-oriented client tool, but there
is also a GUI program called MySQL Workbench, which should be installed. The program
can be downloaded from

http://dev.mysql.com/downloads/workbench/

and here one must again choose platform and the product that you want to download. I
have chosen

Fedora 23 (x86, 64-bit), RPM Package

and again I get the download window:

If you choose Software Installation and click OK, go it all by itself. It takes some time,
but then the tool is installed and you’ve got a desktop icon. If you open the program, you
must log in as root with the password that you have just chosen. Then you can work with
MySQL, administrate the server, create databases, etc. As the first thing you should create a
new user and only use root if the need arises. I created a user called pa, which I have given
DBA privileges. It is of course to high for everyday use, but until you learn to work with
MySQL, it can be quite reasonable.

143
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

JDBC

The JDBC driver can be downloaded from:

https://dev.mysql.com/downloads/connector/j/

Here you must choose

Platform Independent (Architecture Independent), Compressed TAR Archive

and in the subsequent download window, this time select Save File

144
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

The program is downloaded to the folder Downloads. Open a terminal window and change
The program is downloaded to the folder Downloads. Open a terminal window and change
the current directory to this directory:
the current directory to this directory:

cd Downloads

www.job.oticon.dk

145
145
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Final
FInal examples
examples
JAVA
JAVA 6:
JAVA 6: JDBC
6: JDBC AND
JDBC AND DATABASE
AND DATABASE APPLICATIONS
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
FInal examples
examples

The
The file
file downloaded
downloaded isis called
called mysql-connector-java-5.1.38.tar.gz
mysql-connector-java-5.1.38.tar.gz (when(when the the number
number isis
The
The file
file downloaded
downloaded isis called
called mysql-connector-java-5.1.38.tar.gz
mysql-connector-java-5.1.38.tar.gz (when(when the the number
number isis
determined
determined by by the
the version).
version). I’ve
I’ve copied
copied the
the file
file to
to another
another directory
directory (it
(it isis not
not necessary)
necessary)
determined
determined by by the
the version).
version). I’ve
I’ve copied
copied the
the file
file to
to another
another directory
directory (it
(it isis not
not necessary)
necessary)
and
and made
made itit toto my
my current
current directory:
directory:
and made it to my current directory:
and made it to my current directory:
sudo cp mysql-connector-java-5.1.38.tar.gz /usr/local
sudo
sudo cp
cp mysql-connector-java-5.1.38.tar.gz
mysql-connector-java-5.1.38.tar.gz /usr/local
/usr/local
cd /usr/local
cd /usr/local
cd /usr/local

As aa next
As next step,
step, the
the content
content of
of the
the file
file isis unpacked,
unpacked, which
which isis done
done with
with the
the command:
command:
As
As aa next
next step,
step, the
the content
content of
of the
the file
file isis unpacked,
unpacked, which
which isis done
done with
with the
the command:
command:
tar -zxvf mysql-jdbc.tar.gz
tar
tar -zxvf
-zxvf mysql-jdbc.tar.gz
mysql-jdbc.tar.gz

The result is a directory mysql-connector-java-5.1.38, which contains the driver:


The
Theresult
The resultisisisaaadirectory
result directorymysql-connector-java-5.1.38,
directory mysql-connector-java-5.1.38,which
mysql-connector-java-5.1.38, whichcontains
which containsthe
contains thedriver:
the driver:
driver:
cd mysql-connector-java-5.1.38
cd
cd mysql-connector-java-5.1.38
mysql-connector-java-5.1.38

You now must know where your Java runtime system is installed, and it is probably
You
You now
Younow must
nowmust know
mustknow where
knowwhere your
whereyour Java
yourJava runtime
Javaruntime system
systemisisisinstalled,
runtimesystem installed, and
anditititisisisprobably
installed,and probably
probably

/usr/java/jdk1.8.0_102
/usr/java/jdk1.8.0_102
/usr/java/jdk1.8.0_102
/usr/java/jdk1.8.0_102

possibly with a different version number, and back is only to copy the driver to the right
possibly
possibly with
with aaa different
possibly with different version
different version number,
version number, and
number, and back
back isisis only
and back only to
only to copy
to copy the
copy the driver
the driver to
driver to the
to the right
the right
right
place:
place:
place:
place:
sudo cp mysql-connector-java-5.1.38-bin.jar
sudo
sudo cp
cp mysql-connector-java-5.1.38-bin.jar
mysql-connector-java-5.1.38-bin.jar
/usr/java/jdk1.8.0_102/jre/lib/ext
/usr/java/jdk1.8.0_102/jre/lib/ext
/usr/java/jdk1.8.0_102/jre/lib/ext

Then you
Then you are
are ready
ready to
to write
write database
database applications
applications in
in Java.
Java.
Then
Then you
you are
are ready
ready toto write
write database
database applications
applications inin Java.
Java.

This applies
This applies at
at least
least as
as long
long as
as you
you execute
execute the the programs
programs from
from NetBeans,
NetBeans, but
but ifif you
you are
are
This
This applies
applies at
at least
least as
as long
long as
as you
you execute
execute the the programs
programs fromfrom NetBeans,
NetBeans, butbut ifif you
you are
are
performing programs
performing programs fromfrom aa terminal,
terminal, they
they maymay not
not run,
run, and
and you
you are
are told
told that
that Java
Java can
can
performing programs from a terminal, they may not run, and you are
performing programs from a terminal, they may not run, and you are told that Java can told that Java can
not find
not find the
the JDBC
JDBC driver.
driver. The
The reason
reason isis that
that Fedora
Fedora (and
(and other
other Linux
Linux distributions)
distributions) by by
not
not find
find the
the JDBC
JDBC driver.
driver. The
The reason
reason isis that
that Fedora
Fedora (and
(and other
other Linux
Linux distributions)
distributions) by by
default uses
default uses openjdk
openjdk and
and notnot Oracle’s
Oracle’s Java.
Java. They
They are
are two
two solutions
solutions
default
default uses
uses openjdk
openjdk andand not
not Oracle’s
Oracle’s Java.
Java. They
They are
are two
two solutions
solutions

1. To
1. To ensure
ensure that
that the
the JDBC
JDBC driver
driver isis available
available for
for openjdk
openjdk
1.
1. To
To ensure
ensure that
that the
the JDBC
JDBC driver
driver isis available
available for
for openjdk
openjdk
2. To
2. To ensure
ensure that
that Oracle
Oracle java
java isis used
used as
as default
default
2. To ensure that Oracle java is used as default
2. To ensure that Oracle java is used as default

IIIIwill
will show
will
show how
will show
how to
show how
to select
how to
select the
to select
the second
select the
second solution.
the second
solution. First
second solution.
First II entered
solution. First
entered the
First II entered
the folowing
entered the
folowing command:
the folowing
command:
folowing command:
command:
$ java -version
$$ java
java -version
-version
openjdk version "1.8.0_111"
openjdk
openjdk version
version "1.8.0_111"
"1.8.0_111" (build 1.8.0_111-b16)
OpenJDK Runtime Environment
OpenJDK
OpenJDK Runtime
Runtime Environment
Environment (build
(build 1.8.0_111-b16)
1.8.0_111-b16)
OpenJDK 64-Bit Server VM (build 25.111-b16, mixed mode)
OpenJDK
OpenJDK 64-Bit Server VM (build 25.111-b16, mixed
64-Bit Server VM (build 25.111-b16, mixed mode)
mode)

146
146
146
146
146
JAVA
JAVA6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

that
that shows
shows that
that the
the current
current runtime
runtime system
system isis openjdk.
openjdk. Then
Then II add
add an
an alternative
alternative for
for
that
runtimeshows that
system:
runtime system: the current runtime system is openjdk. Then I add an alternative for
runtime system:
$ sudo alternatives --install /usr/bin/
$ sudo
java alternatives
java --install /usr/bin/
/usr/java/latest/bin/java 1
java java /usr/java/latest/bin/java
[sudo] adgangskode for pa: 1
[sudo] adgangskode for pa:

Then I select the new runtime system (Oracle’s java) as default:


Then
Then II select
select the
the new
new runtime
runtime system
system (Oracle’s
(Oracle’s java)
java) as
as default:
default:
$ sudo update-alternatives --config java
$ sudo update-alternatives --config java
There is 3 programms that supplies "java".
There is 3 programms that supplies "java".
Select Command
Select Command
-----------------------------------------------
-----------------------------------------------
*+ 1 /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.111-1.
*+ 1 /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.111-1.
b16.fc23.x86_64/jre/bin/java
b16.fc23.x86_64/jre/bin/java
2 /usr/java/jdk1.8.0_111/jre/bin/java
2
3 /usr/java/jdk1.8.0_111/jre/bin/java
/usr/java/latest/bin/java
3 /usr/java/latest/bin/java
Press enter for the current selection[+], or
Press
enter enter for the
the number for current selection[+],
the selection: 3 or
enter the number for the selection: 3

147
147
147
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

APPENDIX B
The following is a short introduction to SQL, and the purpose is to show the syntax for the
most important statements. Now SQL is not just SQL, and the different database vendors
have their variants of the language, and although the following examples are tested against
a MySQL database server, they will practically all could be used by any database server.
Thus, it will be a number of extensions to SQL, which is not dealt with, and the following
should not be percieved as a complete manual for SQL.

Before addressing the actual SQL language, I will mention a few basic database concepts.

In the past four years we have drilled

81,000 km
That’s more than twice around the world.

Who are we?


We are the world’s leading oilfield services company. Working
globally—often in remote and challenging locations—we invent,
design, engineer, manufacture, apply, and maintain technology
to help customers find and produce oil and gas safely.

Who are we looking for?


We offer countless opportunities in the following domains:
n Engineering, Research, and Operations
n Geoscience and Petrotechnical
n Commercial and Business

If you are a self-motivated graduate looking for a dynamic career,


apply to join our team. What will you be?

careers.slb.com

148
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

A database is a collection of related tables, and a table contains data organized into columns
and rows. As an example is shown a part of a database table for books, where there are
seven columns:

Each column has a name, and the name should be unique within each table. Each column
has a data type that determines which data the column can contain. A row contains data
about a particular book, and the row’s value in a column is called a field and must match
the column’s data type. A row is also called for a record. The value of a particular field can
be null, which simply means that the field has no value, and it is important to note that
it is not the same as 0 or blank.

A column can be assigned constraint’s that one can think of as conditions, the values in
that column must meet. If they do not, the database management system is rejecting the
database operation. The most important constraints are:

-- NOT NULL, which indicates that a column can not contain null values, and the
row thus must have a value in that column.
-- DEFAULT, where you can specify a default value that is used, if there is not given
a value for the column.
-- UNIQUE, which means that the column’s values must be unique.
-- PRIMARY KEY, indicating that all rows in this column should have a unique value
that identifies the record.
-- FOREIGN KEY, which defines a reference to a primary key in another table
(possibly the same table). The column’s value must be the value of a primary key
in the other table or null.
-- CHECK, where it is possible to define that the column’s values must satisfy a
condition.
-- INDEX, defines an index (table of content) for the column’s values.

149
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

The database management system is the family of programs that maintains the database’s
databases, and is a daemon that constantly runs in the background and waiting for requests
from users in form of SQL commands. In addition to performing these commands, it is
also the database management system that validates that the commands can be executed
properly and in this context tests whether the above constraints are respected. The database
management system has to ensure the integrity of the database, and you talk about the
following integrity rules:

1. Entity integritet, which mean that no rows must have a NULL value in the primary
key column and all values in this column are different.
2. Domain integritet, which ensures that the values in a column are in accordance
with the type of the definition and the constraints.
3. Referential integritet, which guarantees that a row can not be deleted if the database
contains a different row (typically in another table), which refers to this row.
4. User defined integritet, where it is possible to define special rules that do not fall
under the three above rules.

These rules help to ensure that data in the database always contains legal values, but they do
not ensure efficiency, which is a matter of how the database is designed and created. There
are several guidelines for good database design, and one of them is called normalization. Very
briefly, it is a variety of conditions a database design must meet. Usually one uses only the
first three (but there are several), and speaking about that the database is in third normal
form. I will not mention normalization of databases here, but refer to books or articles on
database theory or the book Java 7.

A BOOK DATABASE

In order to show specific SQL commands I needs a database to be able to perform them. I
want to use a database which consists of 5 tables. The primary table contains information
about books:

-- the books ISBN


-- the books title
-- the books edition
-- the books publisher year
-- the number of pages in the book

150
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

Books
Booksare arepublished
publishedby bya apublishing
publishinghouse,
house,and
andthere
thereisisalso
alsoa apublishing
publishingtable,
table,that
thata abook
book
can
canrefer
refertotoby
bya aforeign
foreignkey.
key.Similarly
Similarlythethebooks
booksare
aredivided
dividedintointocategories,
categories,and
andthere
thereisisa a
category
categorytable
tableasasa abook
bookcan canrefer
referto.
to.Final
Finalhas
hasa abook
bookoneoneorormore
moreauthors
authorswhose
whosenames
names
are
are stored in a table author, but as the same author may have written several books,ititisis
stored in a table author, but as the same author may have written several books,
necessary
necessarywith witha atable
tablethat
thatcancanrelate
relatebooks
booksand
andauthors.
authors.Correspondingly,
Correspondingly,the thedatabase
databasecan
can
bebecreated
createdwith
withthethefollowing
followingscript
scriptcalled
calledBooks.sql:
Books.sql:

use sys;
drop database if exists books;
create database books;
use books;

drop table if exists written;


drop table if exists author;
drop table if exists book;
drop table if exists publisher;
drop table if exists category;

create table category (


catnr int not null,
name varchar(30) not null,
primary key (catnr));

Linköping University
– Innovative, well ranked, European
Interested in Engineering and its various
branches? Kick-start your career with an
English-taught master’s degree.

liu.se/master

Click here!

151
151
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

create table publisher (


pubnr int not null,
name varchar(40) not null,
primary key (pubnr));

create table author (


autnr int not null,
firstname varchar(50),
lastname varchar(20) not null,
primary key (autnr));

create table book (


isbn char(13) not null,
title varchar(100) not null,
edition int,
year char(4),
pages int,
pubnr int not null,
catnr int,
primary key (isbn),
foreign key (pubnr) references publisher (pubnr),
foreign key (catnr) references category (catnr));

create table written (


isbn char(13) not null,
autnr int not null,
primary key (isbn, autnr),
foreign key (isbn) references book (isbn),
foreign key (autnr) references author (autnr));

AAscript
scriptisissimply
simplya atext
textfile
filecontaining
containingSQLSQLcommands.
commands.IfIfthe
thefile
fileisisopened
openedininMySQL
MySQL
Workbench,and
Workbench, andperformed
performedthe thescript
scriptcreates
createsthe
thedatabase.
database.Preliminary
Preliminaryignore
ignorethe
theindividual
individual
commandsbecause
commands becausethey
theyare
areallalldealt
dealtwith
withbelow.
below.

Afterthe
After thescript
scriptisisdone,
done,you
youhave
haveananempty
emptydatabase,
database,but
butyou
youmust
musthave
havesomething
somethingtotodo
do
with,and
with, andyou
youmust
mustaddadddata
datatotothe
thedatabase.
database.InInthe
thefolder
folderfor
forthis
thisbook
bookthere
thereare
are55text
text
fileswith
files withdata
datafor
forthe
the55tables:
tables:

Category.txt
Category.txt
Publisher.txt
Publisher.txt
Author.txt
Author.txt
Book.txt
Book.txt
Written.txt
Written.txt

152
152
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASE APPLICATIONS
APPLICATIONS Finalexamples
FInal examples

IfIfyou
youcopy
copy these
these files
files to
to the
the /var/lib/mysql-files/data (requires you
/var/lib/mysql-files/data (requires you are
are root)
root) so
so the
the database
database
can
canbebeloaded
loaded with
with data
data using
using thethe following
following script (LoadBooks.sql ):
script (LoadBooks.sql ):

use books;

load data infile '/var/lib/mysql-files/data/Category.txt'


into table category
fields terminated by '\t'
lines terminated by '\r\n';

load data infile '/var/lib/mysql-files/data/Publisher.txt'


into table publisher
fields terminated by '\t'
lines terminated by '\r\n';

load data infile '/var/lib/mysql-files/data/Author.txt'


into table author
fields terminated by '\t'
lines terminated by '\r\n';

load data infile '/var/lib/mysql-files/data/Book.txt'


into table book
fields terminated by '\t'
lines terminated by '\r\n';

load data infile '/var/lib/mysql-files/data/Written.txt'


into table written
fields terminated by '\t'
lines terminated by '\r\n';

Theresult
The resultisis that
that you
you now
now have
have aa simple
simple database
database with
with 55 tables.
tables.

SQLDATA
SQL DATATYPES
TYPES
Asshown
As showninin the
the above
above script
script that
that creates
creates the
the database
database books,
books, then
then each
each column
column has
has aa data
data
type. There are the following options:
type. There are the following options:

- Int, that can contain an integer between -2147483648 and 2147483647.


-- Int, that can contain an integer between -2147483648 and 2147483647.
- Smallint, that can contain an integer between -32768 and 32767.
-- Smallint, that can contain an integer between -32768 and 32767.
- Tinyint, that can contain an integer between 0 and 255.
-- Tinyint, that can contain an integer between 0 and 255.
- Bit, there is 0 or 1 (in MySQL you can also write Bool, that means the same).
-- Bit, there is 0 or 1 (in MySQL you can also write Bool, that means the same).
- Bigint, that can contain an integer between the two integers -9223372036854775808
-- Bigint, that can contain an integer between the two integers -9223372036854775808
and 9223372036854775807.
and 9223372036854775807.
- Numeric (or Decimal ) to decimal numbers between -10^38 +1 and 10^38 -1
-- Numeric (or Decimal ) to decimal numbers between -10^38 +1 and 10^38 -1
- Money to currency values and can contain a value between -922337203685477.5808
-- Money to currency values and can contain a value between -922337203685477.5808
and 922337203685477.5807
and 922337203685477.5807

153
153
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

-- Smallmoney to currencies values from -214748.3648 to 214748.3647


-- Float to floating points from -3.40E + 38 to 3.40E + 38 (the type is also called Real).
-- Double to floating points from -1.79E+308 to 1.79F+308.
-- Datetime to timekeeping from 1. January 1753 to 31 December 9999.
-- Smalldatetime to timekeeping from 1. January 1900 to 6. June 2079.
-- Date to dates on the form YYYYMMDD
-- Time to time on the form HHMMSS
-- Char to text of a fixed length with max 255 characters, where the field is filled
with blanks.
-- Varchar to text of variable length, which can be up to 65535 characters.

In addition, there are two types Text and Blob, which fills the same (the same capacity), but
are used respectively to text and binary data. They come in several varieties:

-- Tinytext and Tinyblob with space for max 255 bytes.


-- Text and Blob with space for max 65535 bytes.
-- Mediumtext and Mediumblob with space for max 16777215 bytes.
-- Longtext and Longblob with space for max 4294967295 bytes.


678'<)25<2850$67(5©6'(*5((

&KDOPHUV8QLYHUVLW\RI7HFKQRORJ\FRQGXFWVUHVHDUFKDQGHGXFDWLRQLQHQJLQHHU
LQJDQGQDWXUDOVFLHQFHVDUFKLWHFWXUHWHFKQRORJ\UHODWHGPDWKHPDWLFDOVFLHQFHV
DQGQDXWLFDOVFLHQFHV%HKLQGDOOWKDW&KDOPHUVDFFRPSOLVKHVWKHDLPSHUVLVWV
IRUFRQWULEXWLQJWRDVXVWDLQDEOHIXWXUH¤ERWKQDWLRQDOO\DQGJOREDOO\
9LVLWXVRQ&KDOPHUVVHRU1H[W6WRS&KDOPHUVRQIDFHERRN

154
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples

The above applies to MySQL, but other databases can have several data types.

In addition to data types, there are similar to other programming languages operators, and
in terms to arithmetical operators and operators for comparison the syntax is almost the
same as in Java. However, there are some other operators, as I will explain in connection
with examples, but the list is as follows:

-- ALL
-- AND
-- ANY
-- BETWEEN
-- EXISTS
-- IN
-- LIKE
-- NOT
-- OR
-- IS NULL
-- UNIQUE

SQL COMMANDS

SQL is a command language, and there are the following commands:

-- CREATE, that is used to create database objects such as tables


-- ALTER, that is used to modify existing objects, such as tables
-- DROP, that is used to delete objects such as tables

These commands are called DDL commands for Data Definition Language.

-- GRANT, that is used to assign the rights for users


-- REVOKE, that is used to remove rights from users

These commands are called DCL commands for Data Control Language.

-- INSERT, which is used to insert a row in a table


-- UPDATE, which is used to modify the content of one or more rows in a table
-- DELETE, which is used to delete one or more rows in a table

155
JAVA
JAVA6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

These
These commands
commands are
are called
called DML
DML commands
commands for
for Data
Data Manipulation
Manipulation Language.
Language.
These commands are called DML commands for Data Manipulation Language.
--- SELECT,
SELECT, which
which isis used
used for
for extracting
extracting rows
rows from
from one
one or
or more
more tables
tables
- SELECT, which is used for extracting rows from one or more tables
This
This command
command isis called
called aa DQL
DQL command
command for
for Data
Data Query
Query Language.
Language.
This command is called a DQL command for Data Query Language.
There
There are
are asas such
such 99 commands
commands so
so SQL
SQL should
should be
be easy
easy to
to learn,
learn, and
and itit also
also is,
is, and
and itit isis only
only
There
the are
last, as
which such
is 9 commands
complex with so
a SQL
very should be
comprehensiveeasy to learn,
syntax. and it also is, and it is only
the last, which is complex with a very comprehensive syntax.
the last, which is complex with a very comprehensive syntax.
Note
Note first
first that
that SQL
SQL does
does not
not differentiate
differentiate between
between small
small and
and capital
capital letters,
letters, but
but in in the
the
Note first
following, that SQL does not differentiate between small and capital letters, but in the
following, II generally
generally write
write SQL
SQL names
names with
with capital
capital letters
letters and
and itit isis only
only because
because itit for
for the
the
following, I generally
reader write is
SQL names with capital letters and it is only because it for the
reader should
should bebe clear
clear what
what is SQL
SQL key
key words.
words.
reader should be clear what is SQL key words.
As
As an
an example
example isis shown
shown aa command
command that
that creates
creates aa database:
database:
As an example is shown a command that creates a database:
CREATE DATABASE books;
CREATE DATABASE books;

If you want to delete the database again, you can do it with the command
IfIfyou
youwant
wanttotodelete
deletethe
thedatabase
databaseagain,
again,you
youcan
cando
doititwith
withthe
thecommand
command
DROP DATABASE books;
DROP DATABASE books;

One must of course be wary of a command as above, that you do not delete a database
One
Onemust
mustofofcourse
coursebebewary
waryofofaacommand
commandasasabove,
above,that
thatyou
youdo
donot
notdelete
deleteaadatabase
database
with data – unless this is exactly what you want.
with data – unless this is exactly what you want.
with data – unless this is exactly what you want.
If the database management system is used to manage multiple databases (and it will always
IfIfthe
thedatabase
databasemanagement
managementsystem
systemisisused
usedtotomanage
managemultiple
multipledatabases
databases(and
(andititwill
willalways
always
be the case), and you opens MySQL Workbench, you must tell which database the SQL
bebethe
thecase),
case),and
andyou
youopens
opensMySQL
MySQLWorkbench,
Workbench,you
youmust
musttell
tellwhich
whichdatabase
databasethetheSQL
SQL
commands should works on. You do this with a command like
commands should works on. You do this with a command
commands should works on. You do this with a command like like
USE books;
USE books;

which makes the database books to the current database.


which
whichmakes
makesthe
thedatabase
databasebooks
bookstotothe
thecurrent
currentdatabase.
database.
Is the database books the current database, you can create a table as follows:
IsIsthe
thedatabase
databasebooks
booksthe
thecurrent
currentdatabase,
database,you
youcan
cancreate
createaatable
tableasasfollows:
follows:
CREATE TABLE publisher (
CREATE TABLEINT
pubnr publisher
NOT (NULL,
pubnr
name INT NOT NOT
VARCHAR(40) NULL,
NULL,
name VARCHAR(40)
PRIMARY KEY (pubnr)); NOT NULL,
PRIMARY KEY (pubnr));

156
156
156
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

Here
Here you
you creates
creates aa table
table named
named publisher.
publisher. The
The table
table has
has two
two columns,
columns, where
where the
the first
first isis
called
calledpubnr
pubnrand andhashasthe
thetype
typeINT
INTandandthus
thusmust
mustcontain
containintegers,
integers,while
whilethe
theother
otherisiscalled
called
name and has type VARCHAR to hold max 40 characters and then can
name and has type VARCHAR to hold max 40 characters and then can contain text. Both contain text. Both
columns
columnsare aredefined
definedNOT NOTNULL,
NULL,and andaarow
rowmust
musthave
haveaavalue
valuefor
forboth
bothpubnr
pubnrand
andname.
name.
Finally
Finallyisisdefined
definedthatthatthe
thecolumn
columnpubnr
pubnrmust
mustbebeprimary
primarykey.key.The
Thecommand
commandisiswritten
writtenon on
several
severallines.
lines.ItItisisnot
notnecessary
necessaryandandisisonly
onlydone
donefor
forthe
thesake
sakeofofreadability,
readability,but
butyou
youshould
should
note
note where there is a comma, as they must be there. The command in question may inin
where there is a comma, as they must be there. The command in question may
addition
additionalso
alsobebewritten
writtenasasfollows:
follows:

CREATE TABLE publisher (


pubnr INT PRIMARY KEY,
name VARCHAR(40) NOT NULL );

When I have not specified NOT NULL for the column pubnr, it is because a column
When I have not specified NOT NULL for the column pubnr, it is because a column
defined as a primary key will automatically be NOT NULL.
defined as a primary key will automatically be NOT NULL.

Welcome to
our world
of teaching!
Innovation, flat hierarchies
and open-minded professors

Study in Sweden -
close collaboration
with future employers
Mälardalen university collaborates with
many employers such as ABB, volvo and
Ericsson

TAKE THE
debajyoti nag
Sweden, and particularly
MDH, has a very impres-
sive reputation in the field

RIGHT TRACK
of Embedded Systems Re-
search, and the course
design is very close to the
industry requirements.
He’ll tell you all about it and
answer your questions at
mdustudent.com
give your career a headstart at mälardalen university
www.mdh.se

157
157
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal examples
FInal examples

Below
Belowisis
isanother
anotherexample
exampleofof
ofaacommand
commandthat
thatcreates
createsaaatable:
table:
Below
Below another
is another example
example of aa command
command that
that creates
creates table:
a table:
CREATE TABLE
TABLE book
book ((
CREATE
CREATE TABLE book (
isbn CHAR(13) NOT NULL,
NULL,
isbn
isbn CHAR(13)
CHAR(13) NOT
NOT NULL,
title VARCHAR(100) NOTNOT NULL,
NULL,
title
title VARCHAR(100)
VARCHAR(100) NOT NULL,
edition INT,
edition
edition INT,
INT,
year CHAR(4),
year
year CHAR(4),
CHAR(4),
pages INT,
pages
pages INT,
INT,
pubnr INT, NOT NULL,
NULL,
pubnr
pubnr INT,
INT, NOT
NOT NULL,
catnr INT,
catnr
catnr INT,
INT,
PRIMARY KEY
KEY (isbn),
(isbn),
PRIMARY
PRIMARY KEY (isbn),
FOREIGN KEY (pubnr) REFERENCES
REFERENCES publisher
publisher (pubnr),
(pubnr),
FOREIGN KEY
FOREIGN KEY (pubnr)
(pubnr) REFERENCES publisher (pubnr),
FOREIGN KEY
KEY (catnr)
(catnr) REFERENCES
REFERENCES category
category (catnr));
(catnr));
FOREIGN
FOREIGN KEY (catnr) REFERENCES category (catnr));

Hereyou
Here
Here youcreates
you createsaaatable
creates tablebook
table bookwith
book with777columns,
with columns,which
columns, whichshould
which shouldcontain
should containinformation
contain informationabout
information aboutaaa
about
Here you creates a table book with 7 columns, which should contain information about a
book.
book. Here
Here
book. Here
Here isisis the
the
is the first
first
the first column
column
first column
column is is
is primary
primary
is primary
primary key. key.
key. The
The
key. The next
next
The next column
column
next column
column is isis defined
defined
is defined NOT
NOT
defined NOTNOT NULL NULL
NULL
NULL
book.
corresponding
corresponding
corresponding to to
to that
that
to that a a book
book
that aa book must
must
book must have
have
must have a a title.
title.
have aa title. The
The
title. The next
next
The next three
three
next three columns
columns
three columns allow
allow
columns allow NULL
NULL
allow NULL values
values
NULL values
values
corresponding
becauseyou
because
because youare
you arewelcome
are welcometoto
welcome tocreate
createaaabook
create bookwithout
book withoutknowing
without knowingwhen
knowing whenthe
when thebook
the bookisis
book isreleased,
released,the
released, the
the
because you are welcome to create a book without knowing when the book is released, the
editionand
edition
edition andthe
and thepage
the pagenumber.
page number.The
number. Thecolumn
The columnpubnr
column pubnrisis
pubnr isforeign
foreignkey
foreign keytoto
key tothethepublisher
the publishertable
publisher tableand
table and
and
edition and the page number. The column pubnr is foreign key to the publisher table and
isdefined
isis definedNOT
defined NOTNULL.
NOT NULL.This
NULL. Thismeans
This meansthat
means thataaabook
that bookmust
book musthave
must haveaaapublisher.
have publisher.The
publisher. Thecolumn
The columncatnr
column catnr
catnr
is defined NOT NULL. This means that a book must have a publisher. The column catnr
isalso
isis alsoaaaforeign
also foreignkey
foreign key(to
key (tothe
(to thetable
the tablecategory),
table category),but
category), butitit
but itmay
maywell
may wellbe
well benull.
be null.This
null. Thismeans
This meansthat
means thataaabook
that book
book
is also a foreign key (to the table category), but it may well be null. This means that a book
neednot
need
need notbe
not beassigned
be assignedtoto
assigned toaacategory,
category,but butifififthere
thereisis isaavalue
valueinininthe
thecolumn,
column,itit itmust
mustbe bethethe
need not be assigned to aa category,
category, but
but there
if there is aa value
value the
in the column,
column, must
it must be
be the
the
numberofof
number
number ofan
anexisting
an existingcategory.
existing category.
category.
number of an existing category.

Ifyou
IfIf youwant
you wanttoto
want todelete
deleteaaatable,
delete table,the
table, thesyntax
the syntaxisis
syntax is
If you want to delete a table, the syntax is
DROP TABLE
TABLE book;
book;
DROP
DROP TABLE book;

whichdeletes
which
which deletesthe
deletes thetable
the tablebook
table bookwith
book withall
with allits
all itsdata.
its data.You
data. Youshould
You shouldnote
should notethat
note thatifififyou
that youinstead
you insteadtries
instead triestoto
tries to
which deletes the table book with all its data. You should note that if you instead tries to
executethe
execute
execute thecommand
the command
command
execute the command
DROP TABLE
TABLE publisher;
publisher;
DROP
DROP TABLE publisher;

wouldget
would
would getan
get anerror
an errorwhen
error whenthe
when thetable
the tablebook
table bookvia
book viathe
via theforeign
the foreignkey
foreign keyrefers
key referstoto
refers to the
the table
table publisher.
publisher.
would get an error when the table book via the foreign key refers to the
the table
table publisher.
publisher.

Itisis
It
ItIt is also
also possible
possible toto modify
modify database
database objects.
objects. As
As an
an example
example the
the following
following command
command adds
adds
is also
also possible
possible toto modify
modify database
database objects.
objects. As
As an
an example
example the
the following
following command
command adds
adds
aaaanew
newcolumn
new
new
columntoto
column
column
to the
the table
to the
table book:
the table
book:
table book:
book:
ALTER TABLE
TABLE book
book ADD
ADD info
info VARCHAR(1024);
VARCHAR(1024);
ALTER
ALTER TABLE book ADD info VARCHAR(1024);

158
158
158
158
JAVA
JAVA6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

Similarly,
Similarly,the
thefollowing
followingcommand
commandisisused
usedtotochange
changethe
thedata
datatype
typeofofthe
thenew
newcolumn:
column:
Similarly, the following command is used to change the data type of the new column:
ALTER
ALTER TABLE
TABLE book
book MODIFY
MODIFY info
info Text;
Text;
ALTER TABLE book MODIFY info Text;

IfIfyou
youwant
wanttotodelete
deletethe
thenew
newcolumn
columnagain,
again,you
youcan
cando
doititwith
withthe
thefollowing
followingcommand:
command:
If you want to delete the new column again, you can do it with the following command:
ALTER TABLE
ALTER book DROP
TABLE book COLUMN info;
DROP COLUMN info;
ALTER TABLE book DROP COLUMN info;

If,If,for
forexample
exampleititisissuch
suchthat
thatthe
thebook’s
book’sedition
editionmust
mustbe
beless
lessthan
than20,
20,you
youcan
canexecute
execute
If,
the for example
thecommand:
command: it is such that the book’s edition must be less than 20, you can execute
the command:
ALTER
ALTER TABLE
TABLE book
book ADD
ADD CONSTRAINT
CONSTRAINT editionCheck
editionCheck CHECK
CHECK (edition
(edition <
< 20);
20);
ALTER TABLE book ADD CONSTRAINT editionCheck CHECK (edition < 20);

where
wherethe
theconstraint
constrainthas
hasbeen
beengiven
givenaaname,
name,sosoyou
youcancanrefer
refertotoititininSQL
SQLcommands.
commands.
where the constraint
Subsequently, has been given a name, so you can refer to it in SQL commands.
Subsequently,one
onecould
couldmodficere
modficerethis
thisconstraint
constraintasasfollows:
follows:
Subsequently, one could modficere this constraint as follows:
ALTER
ALTER TABLE book
TABLE book ADD
ADD CONSTRAINT
CONSTRAINT editionCheck
editionCheck
ALTER
CHECK
CHECK TABLE book
(edition IS ADD CONSTRAINT
NULL OR editionCheck
(edition
(edition IS NULL OR (edition BETWEEN
BETWEEN 1
1 AND
AND 19));
19));
CHECK (edition IS NULL OR (edition BETWEEN 1 AND 19));

there would be a more accurate control.


there
therewould
wouldbe
beaamore
moreaccurate
accuratecontrol.
control.
As a final example the below shows a command that changes the name of a column:
As
Asaafinal
finalexample
examplethe
thebelow
belowshows
showsaacommand
commandthat
thatchanges
changesthe
thename
nameofofaacolumn:
column:
ALTER TABLE
ALTER book CHANGE
TABLE book edition edit
CHANGE edition INT;
edit INT;
ALTER TABLE book CHANGE edition edit INT;

I mention the command because it can be useful, but also because it is an example of a
I Icommand
mentionthe
mention thecommand
commandbecause
whose
because itcan
syntax depends it
can beuseful,
on the be
useful,but
butalso
current database
alsobecause
becauseititisisan
management
anexample
exampleofofaa
system.
commandwhose
command whosesyntax
syntaxdepends
dependson
onthe
thecurrent
currentdatabase
databasemanagement
managementsystem.
system.
There are many other options with the command ALTER but the above gives an impression
There
There are
of theare many
many
syntax other
other
and options
options
what withthe
with
is possible. thecommand
commandALTER
ALTERbut
butthe
theabove
abovegives
givesan
animpression
impression
ofofthe
thesyntax
syntaxand
andwhat
whatisispossible.
possible.

DML COMMANDS
DMLCOMMANDS
DML COMMANDS
The above commands are all examples of DDL commands and thus commands that modify
Theabove
The abovecommands
commandsare areall
allexamples
examplesofofDDL
DDLcommands
commandsand andthus
thuscommands
commands thatmodify modify
the structure of the database. The main use of these commands are in scriptsthatthat create
the
the structure
structure
databases. ofthe
the
Inofthis database.
database.
section The
The
I will main
main
show use
theuse ofofthese
syntax these
of the commands
commands
three DML arecommands,
are ininscripts
scriptsthat
thatcreate
and create
unlike
databases.
databases. InInthis
DDL commands, thissection
section I Iwill
these are will showthe
show
commands the syntax
syntax
that ofofthe
change the three
thethree DML
DML
content commands,
of commands,
the andunlike
tables. and unlike
DDLcommands,
DDL commands,these theseare
arecommands
commandsthatthatchange
changethe thecontent
contentofofthe
thetables.
tables.

In this section and also in the rest of this appendix, it is assumed that the database books
InIn this
arethis sectionand
section
as describedand alsointroduction
in also
the ininthe
therest
restofofand
thisisappendix,
this appendix,ititisis
loaded with assumed
assumed
data thatthe
that
as describedthe databasebooks
database
there. books
areasasdescribed
are describedininthe
theintroduction
introductionand andisisloaded
loadedwith
withdatadataasasdescribed
describedthere.
there.

159
159
159
159
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Final examples
FInal examples

II will
will start
start with
with the
the command
command INSERT,
INSERT, that
that insert
insert aa row
row in
in aa table.
table. As
As an
an example,
example, the
the
following command
following command inserts
inserts aa row
row in
in the
the author
author table:
table:

INSERT INTO author VALUES (186, 'Mogens', 'Trolle');

In
In order
order that
that the
the command
command can
can be executed, there
be executed, there are
are two
two requirements:
requirements:

1.
1. After
After VALUES
VALUES must
must be
be in
in parentheses
parentheses aa value
value for
for each
each of
of the
the three
three columns
columns in
in the
the
table
table and
and the
the types
types must
must match.
match.
2.
2. The value of autnr (the value 186)
The value of autnr (the value 186) must
must not
not already
already exist
exist –
– the
the column
column are primary key
are primary key

In
In many
many ways
ways it
it is
is the
the simplest
simplest INSERT
INSERT command,
command, as
as one
one can
can imagine.
imagine.

Often,
Often, the
the insertion
insertion of
of aa row,
row, however,
however, require
require the
the insertion
insertion of
of rows
rows in
in multiple
multiple tables.
tables. If
If
for example, I want to create the book
for example, I want to create the book

78-7900-910-7,
78-7900-910-7, Afrikas
Afrikas dyreliv
dyreliv publiched
publiched on
on Globe
Globe as
as 1.
1. edition
edition and
and written
written by
by Mogens
Mogens Trolle
Trolle

LIFE SCIENCE IN UMEÅ, SWEDEN


– YOUR CHOICE!
• 32 000 students • world class research • top class teachers
• modern campus • ranked nr 1 in Sweden by international students
• study in English

– Bachelor’s programme in Life Science


– Master’s programme in Chemistry
– Master’s programme in Molecular Biology

Download
brochure
here!

160
160
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
examples

then
then the publisher does not exists and must first be created. When the author isis already
then the
the publisher
publisher does
does not
not exists
exists and
and must
must first
first be
be created.
created. When
When thethe author
author is already
already
created
created (with the command above), there must also be added a row to the table written
created (with the command above), there must also be added a row to the table written
(with the command above), there must also be added a row to the table written
and
and the
the book
book can
can be
be created
created asas follows:
follows:
and the book can be created as follows:

INSERT
INSERT INTO
INTO publisher
publisher VALUES
VALUES (21,
(21, 'Globe');
'Globe');
INSERT INTO book
INSERT INTO book (isbn,
(isbn, title,
title, edition,
edition, pubnr)
pubnr)
VALUES
VALUES ('87-7900-910-7', 'Afrikas dyreliv', 1,
('87-7900-910-7', 'Afrikas dyreliv', 1, 21);
21);
INSERT INTO
INSERT INTO written
written VALUES
VALUES ('87-7900-910-7',
('87-7900-910-7', 186);
186);

The
The first
Thefirst command
firstcommand requires
commandrequires
requiresnono additional
noadditional comments
additionalcomments beyond
commentsbeyond again
beyondagain to
againto be
tobe aware
beaware that
awarethat publisher
thatpublisher
publisher
number
number
number 21 21 must
21 must not
must not already
not already exist.
already exist.
exist.

The
The second
Thesecond command
secondcommand
commanddoes does
doesnot not insert
notinsert values
insertvalues
valuesin in
inall all columns,
allcolumns,
columns,and and therefore
andtherefore
thereforeyou you must
youmust specify
mustspecify
specify
in
in which columns to be inserted values. This is done
in which columns to be inserted values. This is done by listing the column names in
which columns to be inserted values. This is done by
by listing
listing the
the column
column names
names in
in
parentheses
parentheses
parenthesesafterafter the
afterthe table
thetable name.
tablename. Then
name.Then
ThenVALUESVALUES
VALUESmust must specify
mustspecify values
specifyvalues
valuesfor for these
forthese columns.
thesecolumns.
columns.You You
You
should note
should
should note that
note that isbn
that isbn isis
isbn is necessary
necessary because
necessary because itit
because it isis
is the
the primary
the primary key.
primary key. Also
key. Also the
Also the title
the title isis
title is necessary,
necessary,
necessary,
when
when this
when this column
column isis
this column defined
is defined
defined NOT NOT
NOT NULLNULL
NULL and and
and itit it isis ok
is ok that
ok that there
there isis
that there no
is no value
no value
value forfor year
for year and
year and
and
pages,
pages, as the columns may contain NULL values. pubnr is defined NOT NULL, and you
pages, asas the
the columns
columns may
may contain
contain NULL
NULL values.
values. pubnr
pubnr is
is defined
defined NOT
NOT NULL,
NULL, and
and you
you
must
must indicate
must indicate a publishing
indicate aa publishing
publishing number,number,
number, and and
and whenwhen
when the the column
the column is a foreign
column isis aa foreign
foreign keykey
key to to
to thethe table
the table
table
publisher itit
publisher
publisher it must
must be
must be aaa number
be number on
number on an
on an existing
an existing publishers.
existing publishers. ItIt
publishers. It isis
is therefore
therefore necessary,
therefore necessary, that
necessary, that the
that the
the
command
command
commandthat that creates
thatcreates
createsthe the publisher
publisherisis
thepublisher executed
isexecuted
executedbefore before
beforethe the command
thecommand
commandthat that creates
thatcreates
createsthe the book.
thebook.
book.
Note,
Note, finally, that there is not defined a category, although this column (column catnr) isis
Note, finally,
finally, that
that there
there is
is not
not defined
defined a a category,
category, although
although this
this column
column (column
(column catnr)
catnr) is
a foreign
aa foreign
foreign keykey to
key to the
to the table
the table category.
table category. It is not
category. ItIt isis not necessary,
not necessary,
necessary, becausebecause
because the the column
the column allows
column allows
allows NULL NULL
NULL
values, which
values,
values, which in
which in turn
in turn corresponds
turn corresponds to,
corresponds to, that
to, that aaa book
that book does
book does not
does not need
not need
need to to have
have aaa category.
to have category.
category.

Then
Then there
there isis
Then there finally
is finally the
finally the last
the last command,
command, asas
last command, there
there isis
as there not
is not much
not much
much toto say,
to say, but
say, but you
but you should
you should note
should note
note
that
that the
thatthe two
thetwo values
twovalues is a composite
valuesisisaacomposite
compositekey,key, and
key,and each
andeach part
eachpart
partof of the
ofthe key
thekey is a foreign
keyisisaaforeign key,
foreignkey, respectively
key,respectively
respectively
to the
to
to the table
the table book
table book and
book and table
and table author.
table author.
author.

The
The command
The command UPDATE
UPDATE isis
command UPDATE used
is used to
used to change
to change the
change the values
the values in
values in the
in the columns,
the columns, and
columns, and by
and by way
by way of
way of the
of the
the
example,
example, the
example, the following
the following command
following command updates
command updates a row
updates aa row
row inin table
in table book:
table book:
book:

UPDATE
UPDATE book
book SET
SET year
year =
= '2010',
'2010', pages
pages =
= 255
255 WHERE
WHERE isbn
isbn =
= '87-7900-910-7';
'87-7900-910-7';

161
161
161
JAVA
JAVA6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
examples

The
The command isis easy enough to understand. After SET follows a comma-separated list of
The command
command is easy easy enough
enough to to understand.
understand. After
After SETSET follows
follows aa comma-separated
comma-separated list list of
of
column
column names
names and
and values,
values, where
where the
the values
values are
are the
the new
new values.
values. Then
Then there
there isis the
the WHERE
WHERE
column names and values, where the values are the new values. Then there is the WHERE
clause,
clause, which isis followed by aa condition that determines which rows to be modified. AA
clause, which
which is followed
followed by by a condition
condition that that determines
determines whichwhich rows
rows toto be
be modified.
modified. A
WHERE
WHERE clause can be extremely complex, which also will appear from the following about
WHERE clause can be extremely complex, which also will appear from the following about
clause can be extremely complex, which also will appear from the following about
SELECT,
SELECT, but in this case it defines exactly one row. A WHERE may well define multiple
SELECT, but but inin this
this case
case it it defines
defines exactly
exactly oneone row.
row. AA WHERE
WHERE may may well
well define
define multiple
multiple
rows,
rows, and
and where
where appropriate,
appropriate, all
all the
the rows
rows that
that satisfy
satisfy the
the condition
condition are
are updated.
updated. You
You must
must
rows, and where appropriate, all the rows that satisfy the condition are updated. You must
specifically
specifically note that it is not a requirement that an UPDATE command has a WHERE
specifically note
note that
that it it is
is not
not aa requirement
requirement that that anan UPDATE
UPDATE commandcommand has has aa WHERE
WHERE
part,
part, and if not, all the table’s rows are updated. Also note that you can not change the
part, and if not, all the table’s rows are updated. Also note that you can not change the
and if not, all the table’s rows are updated. Also note that you can not change the
value
value of the primary key.
value of
of the
the primary
primary key. key.

As
As another example the following command shows how to set value in aa column to NULL:
As another
another example
example the
the following
following command
command shows
shows how
how to
to set
set value
value in
in a column
column to
to NULL:
NULL:

UPDATE book SET edition = NULL WHERE isbn = '87-7900-910-7';


UPDATE book SET edition = NULL WHERE isbn = '87-7900-910-7';

The
The command
The command assumes
command assumes of
assumes of course
of course that
course that the
that the column
the column allows
column allows NULL
allows NULL values.
NULL values.
values.

Then there
Then there is the DELETE
DELETE command that
that is used toto delete rows.
rows. Suppose you
you have
Then there isis the
the DELETE command
command that isis used
used to delete
delete rows. Suppose
Suppose you have
have
performed
performed the
the following
following command:
command:
performed the following command:

INSERT
INSERT INTO
INTO category VALUES
VALUES (10, 'Test
'Test category');
INSERT INTO category VALUES (10, 'Test category');

that
that inserts
inserts aaa row
that inserts row in
row in the
in the table
the table category.
category. IfIf
table category. you
If you want
you want to
want to delete
to delete the
delete the row
the row again,
row again, you
again, you can
you can do
do itit
can do it
in
in the following way:
in the
the following
following way:
way:

DELETE
DELETE FROM category WHERE catnr = 10;
DELETE FROM
FROM category
category WHERE
WHERE catnr
catnr =
= 10;
10;

So
So itit
it isis simple to delete rows in
in aaa table,
table, but there are
are aaa few
So few things you should be aware
is simple
simple to to delete
delete rows
rows in table, but
but there
there are few things
things you
you should
should bebe aware
aware
of.
of. First,
of. First, the
First, the WHERE
the WHERE
WHERE part part can
part can specify
can specify multiple
specify multiple
multiple rows,rows, and
rows, and if
and ifif soso all
so all rows
all rows that
rows that satisfy
that satisfy the
satisfy the
the
condition
condition
condition afterafter the
after the WHERE
the WHERE
WHERE clause clause
clause areare deleted.
are deleted. Moreover,
deleted. Moreover, it is allowed
Moreover, itit isis allowed
allowed to to completely
to completely omit
completely omit
omit
the WHERE clause, and
and ifif
the so, the command deletes all rows in the table. One should
the WHERE
WHERE clause, clause, and if so,
so, the
the command
command deletesdeletes all
all rows
rows in in the
the table.
table. One
One should
should
therefore
therefore be careful with DELETE, since it’s easy to delete more than the thought is.
therefore be be careful
careful with
with DELETE,
DELETE, since since it’s
it’s easy
easy to
to delete
delete moremore than
than the
the thought
thought is.
is.

In
In this
In this case,
this case, the
case, the table
the table book
table book has
has aaa foreign
book has foreign key
foreign key
key toto the
to the table
the table category,
table category, and
and ifif
category, and there
there isis
if there is aaa book
book
book
that refers to the category with the key 10, the row
row isis not deleted.
deleted. ItIt
It isis
is atat
that least the default,
that refers
refers to
to the
the category
category with
with the
the keykey 10,
10, the
the row is not
not deleted. at least
least the
the default,
default,
but
but there are other options. In the table book could have defined foreign key as follows:
but there
there are
are other
other options.
options. In
In the
the table
table book
book could
could have
have defined
defined foreign
foreign key key as
as follows:
follows:

FOREIGN
FOREIGN KEY
KEY (catnr) REFERENCES
REFERENCES category (catnr)
(catnr) ON DELETE
DELETE SET NULL
NULL
FOREIGN KEY (catnr) REFERENCES category (catnr) ON DELETE SET NULL

162
162
162
162
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
examples

Where
Where appropriate, the references with value 10 for catnr in the table book automatically
Where appropriate,
appropriate, the
the references
references with
with value
value 10
10 for
for catnr
catnr in
in the
the table
table book
book automatically
automatically
be
be set
set to
to NULL.
NULL. Another
Another option
option is
is to
to write:
write:
be set to NULL. Another option is to write:

FOREIGN
FOREIGN KEY
KEY (catnr)
(catnr) REFERENCES
REFERENCES category
category (catnr)
(catnr) ON
ON DELETE
DELETE CASCACE
CASCACE

If
If so,
so, the
the rows
rows of
of the
the table
table book
book that
that refers
refers to
to the
the number
number inin the
the category
category table
table will
will also
also be
be
deleted.
deleted. Cascade
Cascade can
can be
be important
important for
for ensuring
ensuring the
the integrity
integrity of
of the
the database,
database, but
but there
there is
is
still reason to warn a little against this clause. If you have defined foreign key catnr
still reason to warn a little against this clause. If you have defined foreign key catnr as ON as ON
DELETE
DELETE CASCADE,
CASCADE, and and you
you performs
performs the
the command
command

DELETE
DELETE FROM
FROM category
category WHERE
WHERE catnr
catnr == 1;
1;

then
then you
you deletes
deletes not
not only
only aa row
row in
in the
the table
table category,
category, but
but you
you also
also deletes
deletes all
all rows
rows in
in the
the
table
table book
book that
that refers
refers to
to this
this row,
row, and
and that
that is
is the
the vast
vast majority
majority (if
(if not
not som
som of of them
them are
are
prevented to be deleted by a foreign key in the table written).
prevented to be deleted by a foreign key in the table written).

Scholarships

Open your mind to


new opportunities
With 31,000 students, Linnaeus University is
one of the larger universities in Sweden. We
are a modern university, known for our strong
international profile. Every year more than Bachelor programmes in
1,600 international students from all over the Business & Economics | Computer Science/IT |
world choose to enjoy the friendly atmosphere Design | Mathematics
and active student life at Linnaeus University.
Master programmes in
Welcome to join us! Business & Economics | Behavioural Sciences | Computer
Science/IT | Cultural Studies & Social Sciences | Design |
Mathematics | Natural Sciences | Technology & Engineering
Summer Academy courses

163
163
163
JAVA
JAVA6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
examples

THE
THESELECT
THE SELECTCOMMAND
SELECT COMMAND
COMMAND
THE SELECT COMMAND
Then
Then there isisthe SELECT command, which absolutely is the command where there isismost
Then there
there is the
the SELECT
SELECT command,
command, which
which absolutely
absolutely is is the
the command
command wherewhere there
there is most
most
to
to say.
say. The
The simplest
simplest command
command you
you can
can think
think of
of isis aa command
command of
of the
the form:
form:
to say. The simplest command you can think of is a command of the form:

SELECT
SELECT *
* FROM
SELECT * FROM publisher;
FROM publisher;
publisher;

which extracts all rows from the table publisher.


publisher.AAA****means
which means all columns and hence the result
whichextracts
which extractsall
extracts allrows
all rowsfrom
rows fromthe
from thetable
the tablepublisher.
table publisher. A meansall
means allcolumns
all columnsand
columns andhence
and hencethe
hence theresult
the result
result
consists
consists of rows that should contain values from all columns. You can replace * with the
consists of rows that should contain values from all columns. You can replace * with the
consists of
of rows
rows that
that should
should contain
contain values
values from
from all
all columns.
columns. You
You can
can replace
replace ** with
with the
the
names
names of
of the
the columns
columns whose
whose values
values you
you wants
wants
names of the columns whose values you wants to show: to
to show:
show:

SELECT
SELECT title,
SELECT title, pages
title, pages FROM
FROM book;
pages FROM book;
book;

AA SELECT
A SELECT can
SELECT can have
have aaa WHERE
can have WHERE part,
WHERE part, where
part, where you
where you specify
you specify the
specify the rows
the rows to
rows to extract:
to extract:
extract:

SELECT
SELECT title,
title, pages FROM
FROM book
book WHERE
WHERE edition
SELECT title, pages
pages FROM book WHERE edition =
= 4;
4;

The
The
The WHERE
WHERE part
part can
can by
by using
using boolean
boolean operators
operators to
to define
define more
more complex
complex conditions:
conditions:
The WHERE
WHERE part
part can
can by
by using
using boolean
boolean operators
operators to
to define
define more
more complex
complex conditions:
conditions:

SELECT
SELECT title,
SELECT title, pages
title, pages FROM
pages FROM book
FROM book
book
WHERE
WHERE (edition = 1 OR edition =
= 3) AND
AND pages >
> 650 AND
AND pages <
< 700;
WHERE (edition = 1 OR edition =
(edition = 1 OR edition 3)
3) AND pages
pages > 650
650 AND pages
pages < 700;
700;

ItIt
It isis also
is also possible
also possible to
possible to specify
to specify substrings.
specify substrings. As
substrings. As an
As an example
an example the
example the following
the following command
following command extracts
command extracts all
extracts all
all
rows
rows
rows wherewhere title
where title starts
title starts with
starts with the
with the word
the word Java
word Java
Java

SELECT
SELECT title,
title, pages FROM
FROM book
SELECT title, pages WHERE title LIKE
LIKE 'Java%';
'Java%';
pages FROM book
book WHERE
WHERE title
title LIKE 'Java%';

164
164
164
164
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Final
FInal examples
examples
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal examples
examples
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
examples
JAVA FInal

while
while the
the following command extracts all rows where the title contains the word Java
the following command
command extracts all
all rows where
where the title
title contains the
the word Java
while the
while following command extracts all rows where the title contains the word Java
Java
while the following
following command extracts
extracts all rows
rows where the
the title contains
contains the word
word Java
SELECT title, pages FROM book WHERE title LIKE '%Java%';
SELECT
SELECT title,
title, pages
pages FROM
FROM book
book WHERE
WHERE title
title LIKE
LIKE '%Java%';
'%Java%';
SELECT
SELECT title,
title, pages
pages FROM
FROM book
book WHERE
WHERE title LIKE '%Java%';

The rule is that % matches


matches 000
The or more arbitrary characters. As another example extracts the
The rule
The rule is
rule is that
is that %
that % matches
% matches 0 or
or more
or more arbitrary
more arbitrary characters.
arbitrary characters. As
characters. As another
As another example
another example extracts
example extracts the
extracts the
the
The rule
command is that % matches 0 or more arbitrary characters. As another example extracts the
command
command
command
command
SELECT title, year, pages FROM book WHERE year LIKE '19__';
SELECT
SELECT title,
title, year,
year, pages
pages FROM
FROM book
book WHERE
WHERE year
year LIKE
LIKE '19__';
'19__';
SELECT title, year, pages FROM book WHERE year LIKE '19__';

all rows where the year (publisher year) starts with 19 and
and isis followed by two characters,
all rows
all rows where
where the the year
year (publisher
(publisher year)
year) starts
starts with
with 19
19 and is followed
followed by
by two
two characters,
characters,
all
all
sincerows
rows
thewhere
where
rule is the
the year
year
that _ (publisher
(publisher
exactly year)
year)
matches starts
starts
one with
with 19
19
character. and
and is
is followed
followed by
by two
two characters,
characters,
since the
since the rule
rule isis that
that __ exactly
exactly matches
matches one
one character.
character.
since the rule is that _ exactly matches one character.
The following command extracts the first three titles in the table book:
The following
The following command
command extracts
extracts the
the first
first three
three titles
titles in
in the
the table
table book:
book:
The
The following command extracts the first three titles in the table book:
following command extracts the first three titles in the table book:
SELECT title FROM book LIMIT 3;
SELECT
SELECT title
title FROM
FROM book
book LIMIT
LIMIT 3;
3;
SELECT title FROM book LIMIT 3;

LIMIT can also be combined with


with aaa WHERE:
WHERE:
LIMIT can
LIMIT can also
also be
be combined
combined with WHERE:
LIMIT can
LIMIT can also
also be
be combined
combined with
with aa WHERE:
WHERE:
SELECT title FROM book WHERE edition = 2 LIMIT 3;
SELECT
SELECT title
title FROM
FROM book
book WHERE
WHERE edition
edition == 22 LIMIT
LIMIT 3;
3;
SELECT
SELECT title
title FROM
FROM book
book WHERE
WHERE edition
edition =
= 2
2 LIMIT
LIMIT 3;
3;
You should
should be aware
aware that other
other database systems
systems instead of
of LIMIT uses
uses SELECT TOP.
You should
You be aware that other database systems instead of LIMIT uses SELECT TOP.
TOP.
You should be
be aware that
that other database
database systems instead
instead of LIMIT
LIMIT uses SELECT
SELECT TOP.
A SELECT can have an ORDER BY, where the rows are sorted according to values in
AA SELECT can
SELECT can have
have an
an ORDER
ORDER BY, BY, where
where the
the rows
rows are
are sorted
sorted according
according to to values in aaa
values in
A
A SELECT
SELECT
particular can have
can have
column. an ORDER
an the
Thus, ORDER BY, where
BY, command
following the rows
where the sorts are
rows the sorted
are rows
sorted
by according
according
title in to values in
in aa
to valuesorder:
ascending
particular
particular column. Thus, the following command sorts the rows by title in ascending order:
particular column.
particular column. Thus,
column. Thus, the
Thus, the following
the following command
following command sorts
command sorts the
sorts the rows
the rows by
rows by title
by title in
title in ascending
in ascending order:
ascending order:
order:
SELECT isbn, title FROM book ORDER BY title;
SELECT
SELECT isbn,
isbn, title
title FROM
FROM book
book ORDER
ORDER BY
BY title;
title;
SELECT
SELECT isbn,
isbn, title
title FROM
FROM book
book ORDER
ORDER BY
BY title;
title;
If you wish
wish instead that
that the rows
rows are sorted
sorted in descending
descending order, one
one can write:
IfIf you wish
If you
instead that
you wish instead
the rows
instead that the
are sorted
the rows are
in descending
are sorted in
order, one
in descending order,
can write:
order, one can
write:
can write:
SELECT isbn, title FROM book ORDER BY title DESC;
SELECT
SELECT isbn,
isbn, title
title FROM
FROM book
book ORDER
ORDER BY
BY title
title DESC;
DESC;
SELECT
SELECT isbn,
isbn, title
title FROM
FROM book
book ORDER
ORDER BY
BY title
title DESC;
DESC;
You can also sort by multiple criteria. Consider the following command, which extracts
You can
You can also
also sort
sort by
by multiple
multiple criteria.
criteria. Consider
Consider thethe following
following command,
command, which
which extracts
extracts
You
You
isbn, can
can
title also
also
and sort
sort by
edition multiple
by for
multiple
all criteria.
criteria.
rows where Consider
Consider
the the following
thenumber
category followingis command,
command,
1, but so which
which
that the extracts
extracts
rows first
isbn,
isbn, title
title and
and edition
edition for
for all
all rows
rows where
where the
the category
category number
number is
is 1,
1, but
but so
so that
that the
the rows
rows first
first
isbn,
isbn,
are title
title and
sorted and
by edition
edition for
edition, for
andall rows
rows where
allwithin where
each the
the category
category
edition by number
thenumber
title: isis 1,
1, but
but so
so that
that the
the rows
rows first
first
are sorted
are sorted by by edition,
edition, and
and within
within each
each edition
edition byby the
the title:
title:
are
are sorted
sorted by by edition,
edition, and
and within
within each
each edition
edition byby the
the title:
title:
SELECT isbn, title, edition FROM book WHERE catnr = 1
SELECT
SELECT isbn, title,
isbn, title, edition
edition FROM
FROM book
book WHERE
WHERE catnr
catnr == 11
SELECT
ORDER
SELECT isbn, title,
BY edition,
isbn, edition
title, title;
edition FROM
FROM book
book WHERE
WHERE catnr
catnr =
= 1
1
ORDER
ORDER BY
BY edition,
edition, title;
title;
ORDER BY edition, title;

165
165
165
165
165
165
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

GROUP
GROUPBY
BY
GROUP BY
For
For aa SELECT
SELECT you
you can
can also
also define
define GROUP
GROUP BY,BY, which
which indicates
indicates that
that the
the result
result should
should
For a SELECT you can also define GROUP BY, which indicates that the result should
contain
containone
onerow
rowfor
foreach
eachvalue
valueininthe
thecolumn
columnthat
thatwill
willbe
begrouped.
grouped.ForForexample
example
contain one row for each value in the column that will be grouped. For example
SELECT edition FROM book GROUP BY edition;
SELECT edition FROM book GROUP BY edition;

thatwill
that will showall all editions.There
There aresix six rowswith
with thenumbers
numbers 1, 2, 3, …,6.6.ItItisisnotnot so
that willshow
show alleditions.
editions. Thereare are sixrows
rows withthethe numbers1,1,2,2,3,3,…, …, 6. It is notso so
interesting
interesting for the same result could be achieved in other ways, and GROUP BY has also
interestingforforthe
thesame
sameresult
resultcould
couldbe beachieved
achievedininother
otherways,
ways,andandGROUP
GROUPBY BYhas
hasalso
also
only
only of
of interest
interest if
if you
you want
want toto do
do something
something by
by the
the rows
rows that
that fall
fall within
within the
the individual
individual
only of interest if you want to do something by the rows that fall within the individual
groups.If,
groups. If, forexample
example youwere were interestedinindetermining
determining thesum sum of allpages
pages distributed
groups. If,forfor exampleyou you wereinterested
interested in determiningthe the sumofofall all pagesdistributed
distributed
on
on edition you could use the command:
onedition
editionyouyoucould
coulduseusethe
thecommand:
command:
SELECT edition, SUM(pages) FROM book GROUP BY edition;
SELECT edition, SUM(pages) FROM book GROUP BY edition;

YOUR WORK AT TOMTOM WILL


BE TOUCHED BY MILLIONS.
AROUND THE WORLD. EVERYDAY.
Join us now on www.TomTom.jobs
follow us on

#ACHIEVEMORE

166
166
166
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

You
Youshould
shouldnote
notethat
thatthe
theresult
resultshows
shows77rows.
rows.This
Thisisisbecause
becausethere
thereisisaabook
bookininwhich
whichthe
the
You should note that the result shows 7 rows. This is because there is a book in which the
value
valueofofedition
editionisisNULL.
NULL.
value of edition is NULL.
GROUP
GROUPBY BYcan
canbe
becombined
combinedwith
withboth
bothWHERE
WHEREand
andORDER
ORDERBY,
BY,and
andthe
theorder
ordermust
must
GROUP BY can be combined with both WHERE and ORDER BY, and the order must
be
beasasshown
shownbelow:
below:
be as shown below:
SELECT edition, SUM(pages), COUNT(*) FROM book
SELECT edition, SUM(pages), COUNT(*) FROM book
WHERE pages < 1000 GROUP BY edition ORDER BY edition DESC;
WHERE pages < 1000 GROUP BY edition ORDER BY edition DESC;

Hereisisselected
Here selected thegroup
group (theedition),
edition), thesum
sum of allpages
pages withinthe
the group,the
the number
Here is selectedthe
the group(the
(the edition),the
the sumofofall
all pageswithin
within thegroup,
group, thenumber
number
ofof rowswithin
rows withinthe
thegroup,
group,but
butonly
onlyfor
forthe
thebooks
bookswhere
wherethethepage
pagenumber
numberisisless
lessthan
than1000:
of rows within the group, but only for the books where the page number is less than 1000:
1000:

AA WHEREclause
AWHERE
clause defineswhich
WHERE clausedefines
which rowstotobe
defines whichrows
be extracted,and
rows to beextracted,
and youcan
extracted, andyou
can thereforethink
you cantherefore
think of the
therefore thinkofofthethe
WHEREclause
WHERE clauseasasaafilter
filterthat
thatfilters
filtersthe
therows.
rows.Similarly
Similarlywith
withGROUP
GROUPBY BYthere
thereisisaaHAVING
HAVING
WHERE clause as a filter that filters the rows. Similarly with GROUP BY there is a HAVING
clause,that
clause, that is a filterthatthat specifieswhich
which groupstotoinclude.
include. Thesyntax
syntax is as follows:
clause, thatisisaafilter
filter thatspecifies
specifies whichgroups
groups to include.TheThe syntaxisisasasfollows:
follows:
SELECT edition, SUM(pages), COUNT(*) FROM book
SELECT edition, SUM(pages), COUNT(*) FROM book
WHERE pages < 1000 GROUP BY edition
WHERE pages < 1000 GROUP BY edition
HAVING edition = 2 OR edition = 4 OR edition = 6 ORDER BY edition DESC;
HAVING edition = 2 OR edition = 4 OR edition = 6 ORDER BY edition DESC;

167
167
167
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Final
FInal examples
examples
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal examples
FInal examples

where
where the
the HAVING
HAVING clause
clause specifies
specifies that
that only
only groups
groups with
with a value of 2, 4 or 6 should be
where the
where the HAVING
HAVING clause
clause specifies
specifies that
that only
only groups with aaa value
groups with value of
value of 2,
2, 44
of 2, or
or 66
4 or should
6 should be
should be
be
extracted:
extracted:
extracted:
extracted:

IfIf you
you execute
execute the
the command
command
IfIf you
you execute
execute the
the command
command

SELECT edition
SELECT edition
SELECT FROM
edition FROM book;
FROM book;
book;

you
you get
get shown
shown all
all editions,
editions, and
and there
there are
are 87
87 rows.
rows. This
This means
means that
that the
the same
same value
value appears
appears
you get
you get shown
shown all all editions,
editions, and
and there
there are
are 87
87 rows.
rows. This
This means
means that
that the
the same
same value
value appears
appears
several
several times.
times. If you do not want that, you can write
several times. IfIf
several times. you
If you do
you do not
do not want
not want that,
want that, you
that, you can
you can write
can write
write

SELECT DISTINCT
SELECT DISTINCT
SELECT edition
DISTINCT edition FROM
edition FROM book;
FROM book;
book;

which
which simply
which simply means
simply means that
means that all
that all rows
all rows must
rows must be
must be different.
be different.
different.

JOIN
JOIN
JOIN

ItIt
It isis also
is also possible
also possible
possible toto perform
perform aaa SELECT
to perform SELECT command
SELECT command
command that that extracts
that extracts rows
extracts rows from
rows from multiple
from multiple tables,
multiple tables,
tables,
and
and
and we we often
we often talk
often talk about
about aaa JOIN.
talk about JOIN. As
JOIN. As an
As an example
example isis
an example shown
shown aaa JOIN
is shown JOIN command,
JOIN command,
command, that that extracts
that extracts
extracts
the
the title
the title from
title from the
from the book
the book table
book table and
table and the
and the name
the name from
name from the
from the publishers
the publishers table,
publishers table, but
table, but such
but such that
such that there
that there
there
only
only
only are are extracted
are extracted a row
extracted aa row where
row where the
where the value
the value in
value in column
in column pubnr
column pubnr is similar
pubnr isis similar in
similar in the
in the two
the two tables:
two tables:
tables:

SELECT title,
SELECT title,
SELECT name
title, name FROM
name FROM book,
FROM book, publisher
book, publisher WHERE
publisher WHERE book.pubnr ==
book.pubnr
WHERE book.pubnr publisher.pubnr;
= publisher.pubnr;
publisher.pubnr;

Put
Put slightly
Put slightly differently,
slightly differently,
differently, so so are
so are each
are each row
each row of
row of the
of the book
the book table
book table combined
table combined
combined withwith each
with each row
each row
row inin the
in the
the
publisher
publisher table,
publisher table, but
table, but only
but only rows
only rows with
rows with same
with same value
same value
value inin the
in the columns
the columns
columns for for pubnr
for pubnr
pubnr areare included
are included
included in in
in
the
the result.
the result. The
result. The result
The result
result hashas then
has then
then 8787 rows
87 rows with
rows with two
with two columns.
two columns.
columns. You You should
You should note
should note that
note that the
that the two
the two
two
columns
columns names
columns names title
names title and
title and name
and name
name areare unique
are unique determined
unique determined
determined in in the
in the combination
the combination
combination of of the
of the two
the two tables
two tables
tables
but
but both
but both tables
both tables has
tables has a column
has aa column named
column named pubnr,
named pubnr, and
pubnr, and therefore
and therefore it is necessary
therefore itit isis necessary to
necessary to qualify
to qualify the
qualify the name
the name
name
with
with the
with the table
the table name
table name
name in in the
in the WHERE
the WHERE
WHERE part. part.
part.

IfIf you
If you do
you do not
do not specify
not specify concrete
specify concrete columns
concrete columns in
in aaa join
columns in join such
join such as
such as
as

SELECT
SELECT **
SELECT FROM
* FROM book,
FROM book, publisher
book, publisher WHERE
publisher WHERE book.pubnr
book.pubnr ==
WHERE book.pubnr publisher.pubnr;
= publisher.pubnr;
publisher.pubnr;

168
168
168
168
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

the
theresult
resultisisstill
stillthe
the87
87rows,
rows,but
butallallcolumns
columnsfrom
fromboth
bothtables
tablesisisthere
there

Note
Noteespecially
especiallythat
thatthe
thecolumn
columnpubnr
pubnrisisthere
theretwice.
twice.

There
Thereare
areseveral
severaltypes
typesofofJOIN
JOINonontables,
tables,and
andan
anexample
exampleasasthe
theabove
aboveisiscalled
calledan
anINNER
INNER
JOIN and can also be written as follows:
JOIN and can also be written as follows:

SELECT title, name FROM book INNER JOIN publisher


ON book.pubnr = publisher.pubnr;

169
169
JAVA
JAVA6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

An
An INNER
INNER JOINJOIN between
between two
two tables
tables returns
returns rows
rows in
in which
which there
there are
are matches
matches in
in both
both
tables.
tables. An
An INNER
INNER JOIN JOIN (and
(and all
all other
other JOIN
JOIN operations)
operations) can
can also
also be
be combined
combined with
with aa
WHERE
WHERE clause
clause asas such
such

SELECT title, name FROM book INNER JOIN category ON


book.catnr = category.catnr WHERE isbn LIKE '87-%';

that
that returns
returns the
the title
title and
and category
category name
name for
for the
the books
books where
where isbn
isbn starts
starts with
with 87-
87- (all
(all
Danish
Danish titles):
titles):

In
In addition
addition to
to INNER
INNER JOIN,
JOIN, there
there are
are the
the following
following JOIN
JOIN operations:
operations:

--- LEFT
LEFT JOIN,
JOIN, which
which returns
returns all
all rows
rows from
from thethe left
left table,
table, even
even ifif there
there isis no
no match
match
in
in the
the right
right table.
table.
--- RIGHT
RIGHT JOIN,JOIN, which
which returns
returns allall rows
rows of
of the
the right
right table,
table, even
even ifif there
there isis no
no match
match
in
in the
the left
left table.
table.
--- FULL
FULLJOIN,JOIN,which
whichreturns
returnsallallrows
rowseven
evenififthere
thereisisno
nomatch
matchin inone
oneof ofthe
thetwotwotables.
tables.
--- CARTESIAN
CARTESIAN JOIN, JOIN, that
that returns
returns thethe cartesian
cartesian product
product of of the
the two
two tables.
tables.

You
You should
should bebe aware
aware that
that aa FULL
FULL JOIN
JOIN isis not
not supported
supported by
by MySQL.
MySQL. As
As an
an example
example II
will
will show
show aa LEFT
LEFT JOIN:
JOIN:

SELECT title, name FROM book LEFT JOIN category ON


book.catnr = category.catnr WHERE isbn LIKE '87-%';

Note that
Note that in
in principle
principle itit isis the
the same
same JOIN
JOIN asas above,
above, but
but this
this time
time thethe result
result shows
shows seven
seven
rows. This
rows. This isis because
because the
the bookbook table
table has
has aa row,
row, which
which isis NULL
NULL in in the
the column
column catnr
catnr and
and
therefore does
therefore does not
not match
match aa row row inin the
the category
category table,
table, but
but itit isis included
included in in the
the result
result asas
opposed to
opposed to an
an INNER
INNER JOIN JOIN where where there
there must
must bebe aa match
match in in both
both tables.
tables.

170
170
170
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Final
FInal examples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

Below
Below isis aa RIGHT
RIGHT JOIN:
JOIN:
Below
Below is a RIGHT JOIN:
is a RIGHT JOIN:
SELECT title, name FROM book RIGHT JOIN category
SELECT title, name FROM book RIGHT JOIN category
SELECT
ON title, =
book.catnr name FROM book RIGHT JOIN category
category.catnr
ON book.catnr = category.catnr
ON book.catnr
WHERE = '87-%';
isbn LIKE category.catnr
WHERE isbn LIKE '87-%';
WHERE isbn LIKE '87-%';
ItIt also
also shows
shows 66 rows
rows (that
(that isis the
the same
same result
result as
as the
the corresponding
corresponding INNER
INNER JOIN)
JOIN) because
because
It
the also
tableshows 6
categoryrows
does (that
not is the same result as the corresponding INNER JOIN) because
It also
the shows
table 6 rows
category not have
does(that is
havetherows
samewith
rows aa value
result
with as thein
value column
column catnr,
incorresponding which
which does
catnr,INNER not
JOIN)
does match
notbecause
match
the
aathe
row table
in
table category
the book
category does
table.
does not
not have
have rows
rows with
with a
a value
value in
in column
column catnr,
catnr, which
which does
does not
not match
match
row in the book table.
aa row in the book table.
row in the book table.
The
The nextnext command
command isis again
again an an example
example ofof aa INNER
INNER JOIN:JOIN:
The
The next command is again an example of a INNER JOIN:
next command is again an example of a INNER JOIN:
SELECT title, name FROM book, publisher
SELECT title, name FROM book, publisher
SELECT book.pubnr
WHERE title, name
= FROM book, publisher
publisher.pubnr AND isbn LIKE '87-%';
WHERE book.pubnr = publisher.pubnr AND isbn LIKE '87-%';
WHERE book.pubnr = publisher.pubnr AND isbn LIKE '87-%';
and
and the
the result
result isis 77 rows.
rows. IfIf you
you delete
delete the
the JOIN
JOIN condition,
condition, you
you get
get aa CARTESIAN
CARTESIAN JOIN:
JOIN:
and
and the result is 7 rows. If you delete the JOIN condition, you get a CARTESIAN JOIN:
the result is 7 rows. If you delete the JOIN condition, you get a CARTESIAN JOIN:
SELECT title, name FROM book, publisher WHERE isbn LIKE '87-%';
SELECT title, name FROM book, publisher WHERE isbn LIKE '87-%';
SELECT title, name FROM book, publisher WHERE isbn LIKE '87-%';

and the
and the result
result isis 147
147 rows.
rows. The
The reason
reason isis that
that each
each row
row ofof the
the table
table book
book (there
(there are
are 77 meeting
meeting
and the
and WHERE result is
the result clause) 147 rows.
is 147 rows. The reason
The reason is
isallthat
that each
each row
row of the table
of the table book
book (there are
(thereisare 7
7 meeting
meeting
the
the WHERE clause) is combined
isis combined with
with all rows
rows in
in the
the publisher
publisher table
table (which
(which 21),
isis 21), and the
and the
the
the WHERE
WHERE clause)
clause) is combined
combined with
with all
all rows
rows in
in the
the publisher
publisher table
table (which
(which is 21),
21), and
and the
the
result isis aa total
result total ofof 77 ×× 2121 == 147
147 rows.
rows.
result is a total of 7 × 21
result is a total of 7 × 21 = 147 rows.= 147 rows.

ItIt
It isis
is
also possible
also
also
possible to
possible
to join
to
join more
join
more than
more
than two
than
two tables.
two
tables. The
tables.
The following
The
following command
following
command isis aa JOIN
command is a
JOIN between
JOIN
between
between
It is also
three possible
tables to join
showing for more
each than two
title, wheretables.
the The starts
isbn following
with command
87 a row iswith
a JOIN
the between
title and
three
three tables
tables showing
showing for
for each
each title,
title, where
where the
the isbn
isbn starts
starts with
with 87
87 aa row
row with
with the
the title
title and
and
three tables
author’s name showing
name (one
(one row for
row for each
for eachtitle, where
each author):
author): the isbn starts with 87 a row with the title and
author’s
author’s name (one row for each author):
author’s name (one row for each author):
SELECT title, firstname, lastname FROM book
SELECT title, firstname, lastname FROM book
SELECT JOIN
INNER title, firstname,
written lastname =FROM
ON book.isbn book
written.isbn
INNER JOIN written ON book.isbn = written.isbn
written ON
INNER JOIN author ON written.autnr
book.isbn = written.isbn
= author.autnr
INNER JOIN author ON written.autnr = author.autnr
INNER book.isbn
WHERE JOIN author ON '87-%';
LIKE written.autnr = author.autnr
WHERE book.isbn LIKE '87-%';
WHERE book.isbn LIKE '87-%';

By combining (join) book and written you get for each book the author numbers for the
By
By combining
By combining (join) book and written you get for each book the author numbers for the
book’s authors,(join)
combining and book
(join) book
by and
and written
written
combining you
you
this get
get for
result for each
with thebook
each tablethe
book the authoryounumbers
author
author numbers for
for the
can obtain the
the
book’s
book’s
book’s authors,
authors,
authors, and
and
and by
by
by combining
combining
combining this
this
this result
result
result with
with
with the
the
the table
table
table author
author
author you
you
you can
can
can obtain
obtain
obtain the
the
the
authors’ names. The command in question can also be written as follows:
authors’
authors’ names.
authors’ names.
names. TheThe command
The command
command in in question
in question can
question can also
can also be
also be written
be written as
written as follows:
as follows:
follows:
SELECT title, firstname, lastname FROM book, written, author
SELECT title, firstname, lastname FROM book, written, author
SELECT book.isbn
WHERE title, firstname, lastname
= written.isbn FROM
AND book, written,
written.autnr author
= author.autnr
WHERE book.isbn = written.isbn AND written.autnr = author.autnr
WHERE
AND book.isbn
book.isbn = written.isbn
LIKE '87-%'; AND written.autnr = author.autnr
AND book.isbn LIKE '87-%';
AND book.isbn LIKE '87-%';

171
171
171
171
JAVA
JAVA6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

As
Asanother example, shows the following command isbn and title ofofallallmathematics books
As another
another example,
example, shows
shows the
the following
following command
command isbn
isbn and
and title
title of all mathematics
mathematics books
books
published
published
As by Prentice
by Prentice
Prentice
another example, Hall:
Hall:the following command isbn and title of all mathematics books
shows
published by Hall:
published by Prentice Hall:
SELECT
SELECT isbn,
isbn, title
title FROM
FROM book,
book, category,
category, publisher
publisher
WHERE book.catnr
WHERE book.catnr
SELECT = category.catnr
isbn, title= FROM
category.catnr AND book.pubnr
publisher =
AND book.pubnr
book, category, = publisher.pubnr
publisher.pubnr
AND
WHERE category.name
AND category.name LIKE
book.catnr = LIKE '%Matematik%'
'%Matematik%'
category.catnr AND book.pubnr = publisher.pubnr
AND publisher.name
AND category.name
AND LIKE
publisher.nameLIKE '%Prentice
'%Prentice Hall%';
LIKE'%Matematik%' Hall%';
AND publisher.name LIKE '%Prentice Hall%';
As
As appears
Asappears from
appearsfrom the
fromthe JOIN
theJOIN operations
JOINoperations NULL
operationsNULL values
NULLvalues can
valuescan sometimes
cansometimes lead
leadtoto
sometimeslead unexpected
tounexpected
unexpected
results.
results.
As Although
Although
appears
results. from it
Although ithas
the
it has nothing
nothing
JOIN
has todo
toto dowith
operations
nothing do with
NULL
with joins,
joins, please
please
values
joins, can
please note
note thefollowing
the following
sometimes
note the lead to
following syntax
syntax
unexpected
syntax
results. Although it has nothing to do with joins, please note the following syntax
SELECT
SELECT *
* FROM
FROM book
book WHERE
WHERE edition
edition IS
IS NULL;
NULL;
SELECT * FROM book WHERE edition IS NULL;
which
which returns
returns all
all books
books whose
whose value
value for
for edition
edition is
is NULL.
NULL. Similarly,
Similarly, one
one can
can write
write
which
which returns all books whose value for edition is NULL. Similarly, one can write
returns all books whose value for edition is NULL. Similarly, one can write
SELECT *
SELECT * FROM
FROM book
book WHERE
WHERE edition
edition IS
IS NOT
NOT NULL;
NULL;
SELECT * FROM book WHERE edition IS NOT NULL;

172
172
172
JAVA
JAVA6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
examples

When
Whenyouyoujoins
joinsseveral
severaltables
tablesthat
thatcancanoccur
occurname
namematches
matcheswhere
wheretwotwocolumns
columnshashasthe
thesame
same
name. As shown above, one can solve this problem by qualifying the name
name. As shown above, one can solve this problem by qualifying the name with the table with the table
name.
name.ItItcan
canlead
leadtotoaasomewhat
somewhatclumsyclumsysyntax,
syntax,andandadditionally,
additionally,ititmay
maymean
meanthat
thatthere
thereare
are
two columns in the result, with the same name. To solve these problems,
two columns in the result, with the same name. To solve these problems, you can use the you can use the
concept
conceptofofan
analias,
alias,where
whereyou
youcancangive
giveaatable
tableororaacolumn
columnaacustom
customname.
name.The
Thefollowing
following
command determines the title, publisher name and category name for all
command determines the title, publisher name and category name for all Danish books: Danish books:

SELECT title AS Text, P.name AS 'Publisher


name', C.Name AS 'Category name'
FROM book AS B, publisher AS P, category AS C
WHERE B.pubnr = P.pubnr AND B.catnr = C.catnr AND isbn LIKE '87-%';

Thereisisextracted
There extracteddata
datafrom
fromthree
threetables:
tables:book,
book,publisher
publisherand
andcategory,
category,but
butthese
thesetables
tablesare
are
assignednames
assigned namesB,B,PPandandC.C.InInaddition
additionare
areeach
eachofofthe
thethree
threecolumns
columnsassigned
assignedaaname,
name,
and
andyou
youshould
shouldnote
notethat
thatthis
thisnames
namesare
areused
usedininthe
theresult:
result:

SETOPERATIONS
SET OPERATIONS
IfIftwo
twoSELECT
SELECTcommands
commandsare areunion
unioncompatible,
compatible,that
thatisisthey
theyresults
resultsininthe
thesame
samenumber
numberofof
columns,columns
columns, columnsofofthe
thesame
sametypes,
types,and
andthe
thecolumns
columnsininthethesame
sameorder,
order,one
onecan
canperform
perform
the
theUNION:
UNION:

SELECT isbn, title, edition FROM book WHERE isbn LIKE '87-%'
UNION
SELECT isbn, title, edition FROM book WHERE edition = 3 OR edition = 4;

The first
The first command
command returns
returns 77 rows
rows and
and the
the second
second 11
11 rows.
rows. Because
Because UNION
UNION removes
removes
duplicate
duplicaterows,
rows,and
andthere
thereare
aretwo
tworows
rowsthat
thatareareidentical,
identical,the
thecommand
commandwillwillresult
resultinin16
16
rows.
rows.IfIfyou
youinstead
insteadwrites
writes

SELECT isbn, title, edition FROM book WHERE isbn LIKE '87-%'
UNION ALL
SELECT isbn, title, edition FROM book WHERE edition = 3 OR edition = 4;

are duplicate rows retained, and the command will result in 18 rows.
are duplicate rows retained, and the command will result in 18 rows.

173
173
173
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Final
FInal examples
examples

Instead
Instead ofof UNION
UNION you you can
can write
write INTERSECT,
INTERSECT, and and the
the result
result is
is the
the intersection.
intersection. This
This
clause
clause is
is not
not supported
supported byby MySQL.
MySQL. It
It is
is also
also possible
possible to
to write
write EXCEPT
EXCEPT thatthat means
means set
set
difference, but this clause is not supported by MySQL.
difference, but this clause is not supported by MySQL.

SQL
SQL FUNCTIONS
FUNCTIONS
As
As part
part of
of SQL
SQL are
are aa number
number ofof functions
functions that
that can
can be
be used
used in
in SQL
SQL commands.
commands. Above
Above II have
have
already
already used
used the
the SUM()
SUM() andand COUNT().
COUNT(). The The following
following is
is aa listing
listing of
of the
the most
most important
important
of
of those
those functions,
functions, and
and there
there are
are many,
many, but
but they
they can
can be
be divided
divided intointo groups:
groups:

1.
1. general
general functions
functions
2.
2. numeric
numeric functions
functions
3.
3. functions
functions to
to strings
strings
4.
4. functions to date and
functions to date and time
time

and
and in
in addition
addition there
there is
is aa (sometimes
(sometimes large)
large) number
number of
of functions,
functions, depending
depending on
on the
the database
database
product.
product.

GENERAL
GENERAL FUNCTIONS
FUNCTIONS
This
This group
group of
of functions
functions include:
include:

--- COUNT
COUNT
--- MAX
MAX
--- MIN
MIN
--- SUM
SUM
--- AVG
AVG

and
and are
are the
the classic
classic functions,
functions, where
where II above
above has
has used
used COUNT
COUNT and and SUM.
SUM. AsAs an
an example
example
determines
determines the following command the number of books, the total number of pages (total
the following command the number of books, the total number of pages (total
number
number of of pages
pages ofof all
all the
the books),
books), the
the average
average number
number of
of pages,
pages, the
the smallest
smallest number
number ofof
pages
pages and
and the
the largest
largest number
number ofof pages:
pages:

SELECT COUNT(*), SUM(pages), AVG(pages), MIN(pages), MAX(pages) FROM book;

174
174
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

NUMERIC
NUMERICFUNCTIONS
FUNCTIONS
ABS
ABS ACOS
ACOS ASIN
ASIN ATAN
ATAN ATAN2 BIT_AND
ATAN2 BIT_AND
BIT_COUNT BIT_OR
BIT_COUNT BIT_OR CEIL
CEIL CEILING
CEILING CONV
CONV COS
COS
COT
COT DEGREES
DEGREES EXP
EXP FLOOR
FLOOR FORMAT GREATEST
FORMAT GREATEST
INTERVAL LEAST
INTERVAL LEAST LOG
LOG LOG10
LOG10 MOD
MOD OCT
OCT
PI
PI POW
POW POWER
POWER RADIANS RAND
RADIANS RAND ROUND
ROUND
SIN
SIN SQRT
SQRT STD
STD STDDEV TAN
STDDEV TAN TRUNCATE
TRUNCATE

The
The meaning
meaning ofof most
most ofof the
the functions
functions isis indicated
indicated by
by the
the name,
name, and
and you
you can
can not
not be
be
sure that all database systems implements all this functions. Consider as an example
sure that all database systems implements all this functions. Consider as an example the the
following
followingstatements:
statements:

SET @my = 0;
SELECT @my := AVG(pages) FROM book;
SELECT RAND(), PI(), SQRT(2), STDDEV(pages),
SQRT(SUM((pages – @my) * (pages – @my)) / COUNT(*)) AS Sigma FROM book;

WE WILL TURN YOUR CV


INTO AN OPPORTUNITY
OF A LIFETIME

Do you like cars? Would you like to be a part of a successful brand?


Send us your CV on
As a constructer at ŠKODA AUTO you will put great things in motion. Things that will
www.employerforlife.com
ease everyday lives of people all around Send us your CV. We will give it an entirely
new new dimension.

175
175
JAVA
JAVA6:
6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

Here
Here are are the
the results
results of
of the
the first
first three
three functions
functions simple
simple enough,
enough, while
while the
the fourth
fourth function
function
determines
determines the standard-deviation of the books pages. The first statement defines a variable
the standard-deviation of the books pages. The first statement defines a variable
and
and the next statement set this variable equal to the average (mean value) of the number of
the next statement set this variable equal to the average (mean value) of the number of
pages. The value of this variable is used in the last formula, which calculates
pages. The value of this variable is used in the last formula, which calculates the standard the standard
deviation
deviation of of the
the number
number pages.
pages. ItIt isis of
of course
course nono reason
reason for
for that
that calculation,
calculation, because
because there
there
isis aa function
function STDDEV that do the same, but the example should partly show how you
STDDEV that do the same, but the example should partly show how you
can use a variable and partly an example of a complex
can use a variable and partly an example of a complex expression. expression.

FUNCTIONS
FUNCTIONSTO
TOSTRINGS
STRINGS
ASCII
ASCII BIN BIN_LENGTH
BIN BIN_LENGTH
CHAR_LENGTH
CHAR_LENGTH CHARACTER_LENGTH CONCAT_WS
CHARACTER_LENGTH CONCAT_WS
CONCAT CONV ELT
CONCAT CONV ELT
EXPORT_SET FIELD
EXPORT_SET FIELD FIND_IN_SET
FIND_IN_SET
FORMAT HEX
FORMAT HEX INSERT
INSERT
INSTR
INSTR LCASE LEFT
LCASE LEFT
LENGTH
LENGTH LOAD_FILE LOCATE
LOAD_FILE LOCATE
LOWER
LOWER LPAD LTRIM
LPAD LTRIM
MAKE_SET MID
MAKE_SET MID OCT
OCT
OCTET_LENGTH ORD
OCTET_LENGTH ORD POSITION
POSITION
QUOTE
QUOTE REGEXP REPEAT
REGEXP REPEAT
REPLACE
REPLACE REVERT RIGHT
REVERT RIGHT
RPAD
RPAD RTRIM SOUNDEX
RTRIM SOUNDEX
SOUNDEX_LIKE SPACE
SOUNDEX_LIKE SPACE STRCMP
STRCMP
SUBSTR
SUBSTR SUBSTRING SUBSTRING_INDEX
SUBSTRING SUBSTRING_INDEX
TRIM
TRIM UCASE UNHEX
UCASE UNHEX
UPPER
UPPER

Most
Most ofof the
the functions
functions are
are easy
easy enough
enough toto understand,
understand, but but not
not all,
all, and
and there
there itit isis necessary
necessary
to look up the meaning for the function. As an example determines the
to look up the meaning for the function. As an example determines the following statement following statement
the
the title’s
title’s length
length and
and the
the first
first 10
10 characters
characters in
in the
the title
title of
of all
all books
books whose
whose title
title contains
contains
the
the word
word Java:
Java:

SELECT LENGTH(title), SUBSTR(title, 1, 10) FROM book


WHERE title LIKE '%Java%';

176
176
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples

FUNCTIONS
FUNCTIONSTO
TODATE
DATEAND
ANDTIME
TIME
As
Asdiscussed
discussedabove,
above,SQL
SQLtypes
typesfor
fordates
datesclould
clouldbebedifficult
difficulttotouse
usecorrect,
correct,and
andthere
thereare
areaa
number
numberofoffunctions
functionsthat
thatspecifically
specificallyare
areused
usedfor
fordates:
dates:

ADD_DATE
ADD_DATE ADD_TIME CONVERT_TZ
ADD_TIME CONVERT_TZ
CURDATE
CURDATE CURRENT_DATE CURRENT_TIME
CURRENT_DATE CURRENT_TIME
CURRENT_TIMESTAMP CURTIME
CURRENT_TIMESTAMP CURTIME DATE_ADD
DATE_ADD
DATE_FORMAT
DATE_FORMAT DATE_SUB DATE
DATE_SUB DATE
DATE_DIFF DAY
DATE_DIFF DAY DAYNAME
DAYNAME
DAYOFMONTH
DAYOFMONTH DAYOFWEEK DAYOFYEAR
DAYOFWEEK DAYOFYEAR
EXTRACT
EXTRACT FROM_DAYS FROM_UNIXTIME
FROM_DAYS FROM_UNIXTIME
HOUR
HOUR LAST_DAY LOCALTIME
LAST_DAY LOCALTIME
LOCALTIMESTAMP MAKEDATE
LOCALTIMESTAMP MAKEDATE MAKETIME
MAKETIME
MICROSECOND MINUTE
MICROSECOND MINUTE MONTH
MONTH
MONTHNAME NOW
MONTHNAME NOW PERIOD_ADD
PERIOD_ADD
PERIOD_DIFF
PERIOD_DIFF QUATER SEC_TO_TIME
QUATER SEC_TO_TIME
SECOND
SECOND STR_TO_DATE SUBDATE
STR_TO_DATE SUBDATE
SUBTIME
SUBTIME SYSDATE TIME_FORMAT
SYSDATE TIME_FORMAT
TIME_TO_SEC TIME
TIME_TO_SEC TIME TIMEDIFF
TIMEDIFF
TIMESTAMP
TIMESTAMP TIMESTAMPADD TIMESTAMPDIFF
TIMESTAMPADD TIMESTAMPDIFF
TO_DAYS
TO_DAYS UNIX_TIMESTAMP UTC_DATE
UNIX_TIMESTAMP UTC_DATE
UTC_TIME
UTC_TIME UTC_TIMESTAMP WEEK
UTC_TIMESTAMP WEEK
WEEK_DAY
WEEK_DAY WEEKOFYEAR YEAR
WEEKOFYEAR YEAR
YEARWEEK
YEARWEEK

As
Asthe
thetable
tableshows,
shows,there
thereare
aremany
manyfunctions
functionsand
andititisisnot
notsosoeasy
easytotofigure
figureout
outthe
themeaning
meaning
ofofall
allofofthem,
them,but
butthe
theresult
resultisisthat
thatthere
thereare
aremany
manyopportunities
opportunitiestotomanipulate
manipulatedate
dateand
and
time
timeininSQL.
SQL.As Asaasmall
smallexample,
example,the thefollowing
followingstatement
statementuse usetwo
twoofofthis
thisfunctions:
functions:

SET @d = CURDATE();
SET @t = CURTIME();
SELECT @d, @T;

177
177
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Final
FInal examples
examples

VIEW’S
VIEW’S
AA view
view isis basically
basically nothing
nothing more
more than
than aa SQL
SQL statement
statement that
that isis stored
stored in in the
the database,
database, but
but
itit can
can be
be seen
seen as
as aa form
form ofof virtual
virtual table,
table, as
as you
you inin principle
principle can
can use use itit in
in the
the same
same way,
way, as
as
you
you uses
uses other
other tables.
tables. AA view
view can
can bebe created
created onon basis
basis of
of one
one or
or more
more tables,
tables, but
but what
what you
you
can do with a view is determined by how it is created. The
can do with a view is determined by how it is created. The purpose of a view ispurpose of a view is

to
to structure
structure the
the content
content of
of aa database
database corresponding
corresponding to
to the
the users’
users’ use
use of
of the
the database
database

limiting
limiting access
access to
to the
the data
data that
that users
users can
can work
work with
with

allowing
allowing data
data from
from multiple
multiple tables
tables to
to appear
appear as
as aa single
single table
table

In
In MySQL
MySQL Workbench
Workbench you
you can
can create
create aa view
view by
by right-click
right-click on
on Views
Views (the
(the tab
tab SCHEMA)
SCHEMA)
and choose Create View. You then gets the following skeleton:
and choose Create View. You then gets the following skeleton:

CREATE VIEW 'new_view' AS

Develop the tools we need for Life Science


Masters Degree in Bioinformatics

Bioinformatics is the
exciting field where biology,
computer science, and
mathematics meet.

We solve problems from


biology and medicine using
methods and tools from
computer science and
mathematics.

Read more about this and our other international masters degree programmes at www.uu.se/master

178
178
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS Final
APPLICATIONS FInal examples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

As
As an
an example,
example, you
you can
can write
write the
the following
following view:
view:
As an example, you can write the following view:
CREATE VIEW Prentice_hall AS SELECT isbn, title, edition, year, pages
CREATE VIEW
FROM book Prentice_hall
WHERE pubnr = 2;AS SELECT isbn, title, edition, year, pages
FROM book WHERE pubnr = 2;

which defines
which defines aa view
view called
called Prentice_hall
Prentice_hall thatthat for
for all
all books
books where
where pubnr
pubnr areare 22 extracts
extracts the
the
which
isbn, defines a view called Prentice_hall that for all books where pubnr are 2 extracts the
isbn, title,
title, edition,
edition, year
year and
and pages.
pages. That
That isis the
the view
view ofof columns
columns in
in the
the table
table book
book ofof all
all books
books
isbn, title, edition,
published year and
Hall.pages.
When That
youis then
the
thenview
clickofApply,
columns
Apply, in theWorkbench
MySQL table book of
Workbench all books
creates the
published by by Prentice
Prentice Hall. When you click MySQL creates the
published
following by Prentice Hall. When you then click Apply, MySQL Workbench creates the
following view:
view:
following view:
CREATE
CREATE
ALGORITHM = UNDEFINED
ALGORITHM
DEFINER = = UNDEFINED
'pa'@'%'
DEFINER = 'pa'@'%'
SQL SECURITY DEFINER
SQL SECURITY DEFINER
VIEW 'books'.'Prentice_hall' AS
VIEW 'books'.'Prentice_hall' AS
SELECT
SELECT
'books'.'book'.'isbn' AS 'isbn',
'books'.'book'.'isbn'
'books'.'book'.'title' AS
AS 'isbn',
'title',
'books'.'book'.'title' AS
'books'.'book'.'edition' AS 'title',
'edition',
'books'.'book'.'edition'
'books'.'book'.'year' AS AS 'edition',
'year',
'books'.'book'.'year' AS 'year',
'books'.'book'.'pages' AS 'pages'
'books'.'book'.'pages' AS 'pages'
FROM
FROM
'books'.'book'
'books'.'book'
WHERE
WHERE
('books'.'book'.'pubnr' = 2)
('books'.'book'.'pubnr' = 2)
This view may then be used in the same way as the other tables, and for example you
This view may then be used in the same way as the other tables, and for example you
can
Thiswrite:
view may then be used in the same way as the other tables, and for example you
can write:
can write:
SELECT * FROM Prentice_hall;
SELECT * FROM Prentice_hall;

Indeed,
Indeed, one
one can
can also
also to
to some
some extent
extent perform
perform SQL
SQL INSERT,
INSERT, UPDATE
UPDATE and and DELETE
DELETE
Indeed,
statementsone can also to some extent perform SQL INSERT, UPDATE and DELETE
statements in
in aa view.
view. Consider
Consider as
as an
an example
example the
the following
following view,
view, which
which extracts
extracts first
first and
and
statements
last
last names in
names of a
of all view. Consider
all authors
authors where as
where the an example
the last
last name the
name starts following
starts with
with aa K:
K:view, which extracts first and
last names of all authors where the last name starts with a K:
CREATE VIEW knames AS SELECT DISTINCT firstname, lastname
CREATE VIEW
FROM author knames lastname
WHERE AS SELECT DISTINCT
LIKE 'K%'; firstname, lastname
FROM author WHERE lastname LIKE 'K%';

If you then performs the statement


IfIf you
you then
then performs
performs the
the statement
statement
SELECT * FROM knames;
SELECT * FROM knames;

179
179
179
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS Final
APPLICATIONS FInalexamples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal examples
FInal examples
you
you will see that the view contains 8 rows. If you then performs the following statements:
you will
will see
see that
that the
the view
view contains
contains 88 rows.
rows. If
If you
you then
then performs
performs the
the following
following statements:
statements:
you
you will see that the view contains 8 rows. If you then performs the following statements:
will see that the view contains 8 rows. If you then performs the following statements:
INSERT INTO
INTO author
author VALUES (187, 'Poul', 'Klausen');
INSERT VALUES (187, 'Poul', 'Klausen');
select
INSERT * from
INTO knames;
select
INSERT INTO author VALUES
* author
from knames;
VALUES (187,
(187, 'Poul',
'Poul', 'Klausen');
'Klausen');
select
select *
* from
from knames;
knames;
you
you will
you will see
will see that
see that the
that the view
the view knames
view knames now
knames now has
has 99
now has rows.
9 rows. This
rows. This means
This means that
means that after
that after the
after the table
the table author
table author
author
is
isyou
you updated
will
updated seeis
is also
that
also
will seeis that
is updated the
the view
view
view
also the view updated.
knames
updated.now has 9 rows. This means that after the table author
updated.
view knames now has 9 rows. This means that after the table author
is
is updated
updated is is also
also the
the view
view updated.
updated.
Next,
Next, if you
Next, ifif you try:
you try:
try:
Next, if
Next, if you
you try:
try:
INSERT INTO knames VALUES ('Jens', 'Kristensen');
INSERT INTO knames VALUES ('Jens', 'Kristensen');
INSERT
INSERT INTO
INTO knames
knames VALUES
VALUES ('Jens',
('Jens', 'Kristensen');
'Kristensen');
you
you get
get an
an error
error where
where youyou are
are told
told that
that the
the parent
parent table
table can
can not
not bebe updated.
updated. OfOf course
course itit
you
is
you get
not
get an
soan error
strange,
error where
because
where you
you are
there
are told
is that
not
told the
enough
that the parent table
information
parent table can not
(there
can not be
is
be updated.
not an Of
author
updated. Of course
number)
course itit
you
is notgetsoan error where
strange, because you are is
there told
notthat the parent
enough table can
information notisbenot
(there updated. Of number)
an author course it
isis
to not
not so
create
so strange,
a row
strange, because
in the
because there
author
there isisnot
table. enough
Consider
not enough information
the following
information (there
view:
(there isisnot
not an
an author
author number)
number)
is
to not so strange,
create a row inbecause theretable.
the author is notConsider
enough theinformation
following(there
view: is not an author number)
toto create aa row in the author table. Consider the following view:
to create a row in the author table. Consider the following view:
create row in the author table. Consider the following view:
CREATE
CREATE VIEW lnames
lnames AS
AS SELECT
SELECT autnr,
autnr, firatname, lastname
VIEW firatname, lastname
FROM author
CREATE WHERE lastname LIKE 'L%';
CREATE VIEW
FROM author
VIEW lnames
lnames AS SELECT autnr, firatname,
WHERE AS SELECT
lastname autnr,
LIKE 'L%';
firatname, lastname
lastname
FROM author
FROM author WHERE lastname
WHERE lastname LIKE
LIKE 'L%';
'L%';
that
that this
this time
time defines
defines aa column
column to
to all
all columns
columns in
in the
the author
author table.
table. Perform
Perform now
now the
the statement:
statement:
that
thatthis time defines a column to all columns in the author table. Perform now the statement:
that this time defines a column to all columns in the author table. Perform now the statement:
this time defines a column to all columns in the author table. Perform now the statement:
INSERT INTO lnames VALUES (1000, 'Knud', 'Larsen');
INSERT INTO lnames VALUES (1000, 'Knud', 'Larsen');
INSERT
INSERT INTO
INTO lnames
lnames VALUES
VALUES (1000,
(1000, 'Knud',
'Knud', 'Larsen');
'Larsen');
and
and you
you will will see
see that
that both
both the
the view
view and
and the
the original
original table
table isis updated.
updated. This
This means
means that
that an
an
update
and
and you
you will
update of the
will view
see
see also
that
that bothupdates
both the the
view
the view parent
and thetable, but
original
and thetable,
original there
table
table are
is the following
updated.
thereisisare
updated. This conditions:
means
This means that
that an
an
and you of thesee
will view
thatalso
bothupdates the and
the view parent
the originalbuttable the following
updated. conditions:
This means that an
update of
update of the
the view
view also
also updates
updates the
the parent
parent table,
table, but
but there
there are
are the
the following
following conditions:
conditions:
update of the view also updates the parent table, but there are the following conditions:
-- the
the SELECT
SELECT statement
statement may
may not
not use
use DISTINCT
DISTINCT
-- the SELECT statement may
the SELECT statement may not use not contain
use functions
DISTINCT
DISTINCT
contain functions
-- the SELECT statement may not use DISTINCT
-- the
the SELECT statement may not contain functions
SELECT statement may not contain operators
functions
operators
-- the SELECT statement may not contain functions
-- the SELECT statement may
the SELECT statement may not containnot use ORDER
contain
use ORDER BY
operators
operators
BY
-- the SELECT statement may not contain operators
-- the SELECT
the SELECT statement
SELECT statement can
may only
not
may only
statement may
can use one
ORDER
not use ORDER table
one tableBY BY
BY
-- the not use ORDER
-- the SELECT
SELECT statement’s
statement
SELECT statement’s
the SELECT
SELECT statement canWHERE
can only
WHERE part
use
only use may
one
one
partone
may not
not use
table
table use aa SELECT
SELECT statement
statement (se
(se below)
below)
-- the statement can only use table
-- the SELECT
SELECT
SELECT
theSELECT statement
statement’s
statement’s
SELECTstatement’s may
WHERE
WHERE
statement WHERE
may not use
partGROUP
may
partGROUP
not part
use not
may not BY BY
use or
a
use or HAVING
SELECT
a SELECT
HAVING statement
statement (se below)
(se below)
-- the may not use a SELECT statement (se below)
-- the SELECT
SELECT
the SELECT statement
statement
statement
SELECTstatement must
may
may
statementmaymust include
not use
not all
use GROUP
GROUP columns
BY or
BY from
or HAVINGthe
the parent table that
HAVING parent table that is
-- the SELECT notinclude all columns
use GROUP BY orfrom HAVING is
-- the defined
the NOT
SELECT
SELECT
defined NULL
statement
statement
NOTstatement
NULL must must
must include all columns from the parent table that is
include all columns from the parent table that is
-- the SELECT include all columns from the parent table that is
defined NOT
defined NOT NULL NULL
defined NOT NULL

180
180
180
JAVA
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS Final
FInal examples
examples

INNER SELECT STATEMENTS

It is possible to use an inner SELECT statement in a WHERE clause where an inner


SELECT returns data that is used in the condition. An inner SELECT can be used both
in a SELECT, INSERT, UPDATE and DELETE – typically associated with operators. A
typical example is, using SELECT IN:

SELECT isbn, title FROM book WHERE pubnr IN


(SELECT pubnr FROM publisher WHERE
name = 'Prentice Hall' OR name = 'Addison Wesley');

The result is isbn and title of all books published by either Prentice Hall or Addison Wesley.
The result is isbn and title of all books published by either Prentice Hall or Addison Wesley.
Of course one can achieve the same otherwise, but SELECT IN is easy to understand.
Of course one can achieve the same otherwise, but SELECT IN is easy to understand.

Copenhagen
Master of Excellence cultural studies
Copenhagen Master of Excellence are
two-year master degrees taught in English
at one of Europe’s leading universities religious studies

Come to Copenhagen - and aspire!

Apply now at science


www.come.ku.dk

181
181
JAVA
JAVA6:6:JDBC
JDBCAND
ANDDATABASE
DATABASEAPPLICATIONS
APPLICATIONS Final
FInalexamples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

As
Asanother
anotherexample,
example,creates
createsthe
thefollowing
followingscript
scripta anew
newtable
tablewith
withallallthe
themath
mathbooks
bookswhen
when
As another example, creates the following script a new table with all the math books when
the
thetable
tablemust
mustcontain
containthe
thesame
samecolumns
columnsasastable
tablebook,
book,but
butexcept
exceptcolumn
columncatnr:
catnr:
the table must contain the same columns as table book, but except column catnr:

use books;
use books;

create table math (


create table math (
isbn char(13) not null,
isbn char(13) not null,
title varchar(100) not null,
title varchar(100) not null,
edition int,
edition int,
year char(4),
year char(4),
pages int,
pages int,
pubnr int not null,
pubnr int not null,
primary key (isbn),
primary key (isbn),
foreign key (pubnr) references publisher (pubnr));
foreign key (pubnr) references publisher (pubnr));

INSERT INTO math (isbn, title, edition, year, pages, pubnr)


INSERT INTO math (isbn, title, edition, year, pages, pubnr)
SELECT isbn, title, edition, year, pages, pubnr FROM book WHERE catnr = 2;
SELECT isbn, title, edition, year, pages, pubnr FROM book WHERE catnr = 2;

Whatisisinteresting
What interesting is thelast
last INSERTINTO
INTO statementthat
that insertsdata
data froma aSELECT.
SELECT.
What is interestingisisthe
the lastINSERT
INSERT INTOstatement
statement thatinserts
inserts datafrom
from a SELECT.

STOREDPROCEDURES
STORED PROCEDURES
STORED PROCEDURES
I IIwill
willconclude
conclude thisappendix
will concludethis
appendix witha avery
this appendixwith
very briefintroduction
with a verybrief
introduction to storedprocedures,
brief introductiontotostored
procedures, whichisis
stored procedures,whichwhich is
actually
actually a large area. A stored procedure is a routine consisting of SQL statements thatare
are
actuallya alarge
largearea.
area.AAstored
storedprocedure
procedureisisa aroutine
routineconsisting
consistingofofSQL
SQLstatements
statementsthatthat are
storedon
stored on thedatabase
database servertogether
together withthethe databasetables,
tables, andthethe ideaisisofofcourse
course
stored onthe the databaseserver
server togetherwith
with thedatabase
database tables,andand theideaidea is of course
toto savethe
tosave
the SQLprocedures
save theSQL
procedures whichare
SQL procedureswhich
are oftenneeded,
which areoften
needed, butalso
often needed,but
also thata astored
but alsothat
stored procedureisis
that a storedprocedure
procedure is
translatedinto
translated intoananinternal
internalformat
formatand
andthus
thusisiseffective.
effective.
translated into an internal format and thus is effective.

BelowI Iwill
Below will showa afew
few examplesofofsimple
simple procedures,andand howtheythey arecreated
created using
Below I willshow
show a fewexamples
examples of simpleprocedures,
procedures, andhowhow theyare are createdusing
using
MySQL
MySQL Workbench. In the database right-click on Stored Procdures and select Create Stored
MySQLWorkbench.
Workbench.InInthe
thedatabase
databaseright-click
right-clickononStored
StoredProcdures
Procduresand
andselect
selectCreate
CreateStored
Stored
Procedure
Procedure and
and MySQL
MySQL Workbench
Workbench creates
creates a a skeleton:
skeleton:
Procedure and MySQL Workbench creates a skeleton:

CREATE PROCEDURE 'new_procedure' ()


CREATE PROCEDURE 'new_procedure' ()
BEGIN
BEGIN

END
END

You
Youcan
canthen
thenwrite
writea astored
storedprocedure
procedurenamed
namedHello
Helloasasfollows:
follows:
You can then write a stored procedure named Hello as follows:

CREATE PROCEDURE Hello ()


CREATE PROCEDURE Hello ()
BEGIN
BEGIN
SELECT 'Hello World';
SELECT 'Hello World';
END
END

182
182
182
JAVA
JAVA6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
examples
JAVA 6: JDBC AND DATABASE APPLICATIONS FInal examples

and
and
and ifif
you
if you
youthen
then
thenclick
click
clickApply
Apply
Applythe
the
theprocedure
procedure
procedureisis
istranslated,
translated,
translated,and
and
and ifif
there
if there
thereisis
isno
no
noerrors,
errors,
errors,itit
itisis
isstored
stored
stored
and
ininthe if you then
database click
and Apply
MySQL the procedure
Workbench is
will translated,
show the and if
finished there
code:is no errors, it is stored
in the
the database
database and
and MySQL
MySQL Workbench
Workbench will
will show
show the
the finished
finished code:
code:
in the database and MySQL Workbench will show the finished code:
USE
USE 'books';
'books';
USE 'books';
DROP
DROP procedure
procedure IF
IF EXISTS
EXISTS 'Hello';
'Hello';
DROP procedure IF EXISTS 'Hello';

DELIMITER $$
DELIMITER $$
DELIMITER $$
USE 'books'$$
USE 'books'$$
USE 'books'$$
CREATE PROCEDURE
CREATE PROCEDURE Hello
Hello ()
()
CREATE PROCEDURE Hello ()
BEGIN
BEGIN
BEGIN
SELECT 'Hello
SELECT 'Hello World';
World';
SELECT 'Hello World';
END$$
END$$
END$$

DELIMITER
DELIMITER ;
;
DELIMITER ;

The
The
The firstthing
first thingthat
thathappens
happensisis thatthe
that theprocedure
procedureisis deletedifif
deleted thereisis
there alreadya aaprocedure
already procedure
The first
first thing
thing that
that happens
happens is is that
that the
the procedure
procedure is
is deleted
deleted ifif there
there is
is already
already a procedure
procedure
withthe
with
with thesame
the samename.
same name.Next,
name. Next,define
Next, definea aapunctuation
define punctuationused
punctuation usedtoto
used tomark
marktoto
mark toMySQL
MySQLthat
MySQL thatthe
that theprocedure
the procedure
procedure
with the same name. Next, define a punctuation used to mark to MySQL that the procedure
ends.
ends.
ends. Bydefault
By defaultititisisa aadollar
dollarsign.
sign.After
Afterthe
theprocedure
procedureisis translatedand
translated andsaved,
saved,itit canbebe
can
ends. ByBy default
default it
it is
is a dollar
dollar sign.
sign. After
After the
the procedure
procedure isis translated
translated andand saved,
saved, itit can
can be
be
performed
performed
performed as
as
as follows:
follows:
follows:
performed as follows:
CALL
CALL Hello;
Hello;
CALL Hello;

and
and the
the result
result isthat
thatthe
theprocedure
procedureprints
printsHello
HelloWorld
Worldon
onthe
thescreen.
screen.
and
andthe resultisis
theresult is that
that the
the procedure
procedure prints
prints Hello
Hello World
World on
on the
the screen.
screen.

ItIt
It isobviously
Itisis
obviouslynot
is obviously
nota aaparticularly
obviously not
particularlyinteresting
not a particularly
interestingprocedure,
particularly interesting
procedure,but
interesting procedure,
butitit
procedure, but
but it
shows
shows
itshows
showsthe
the
the principle
principle
theprinciple
and
and
principleand
that
that
andthat
that
is
isis simply
simply
simply the
the
the case
case
case that
that
that one
one
one oror
or more
more
more SQL
SQL
SQL statements
statements
statements can
can
can be
be
be executed
executed
executed under
under
under a a
a common
common
common
is simply the case that one or more SQL statements can be executed under a common
name.
name. Inaddition
additiontoto seeing some more examples, there are basically two things that must
name.InIn
name. In addition
addition to seeing
toseeing some
seeingsome more
somemore examples,
moreexamples, there
examples,there are
thereare basically
arebasically two
basicallytwo things
twothings that
thingsthat must
thatmust
must
be
be addressed,
addressed,
bebeaddressed, namely
namely parameters
parameters and
and program
program logic.
logic.
addressed,namely
namelyparameters
parametersandandprogram
programlogic.
logic.

As
As anexample
exampleisis below shown a procedure, that calculate the number og books, where the
Asanan
As an example
example is below
isbelow shown
showna aaprocedure,
belowshown procedure,
procedure,thatthat calculate
thatcalculate the
calculatethe number
thenumber
numberogog books,
ogbooks, where
books,where the
wherethe
the
number
number
number of
of
of pages
pages
pages isis
is greater
greater
greater than
than
than or
or
or equal
equal
equal to
to
to a a
a and
and
and less
less
less than
than
than or
or
or equal
equal
equal to
to
to b,
b,
b, and
and
and where
where
where a a
a and
and
and
number of pages is greater than or equal to a and less than or equal to b, and where a and
b
b areinput
are inputparameters.
parameters.The Theresult
resultisis
is saved
savedinin
in anoutput
outputparameter
parameterc:c:
c:
are input
bbare input parameters.
parameters. TheThe result saved inanan
result issaved an output
output parameter
parameter c:
CREATE
CREATE PROCEDURE
PROCEDURE 'counter'
'counter' (IN
(IN aa int,
int, IN
IN b
b int,
int, OUT
OUT c
c int)
int)
CREATE PROCEDURE 'counter' (IN a int, IN b int, OUT c int)
BEGIN
BEGIN
BEGIN
SELECT
SELECT count(isbn)
count(isbn) FROM
FROM book
book WHERE
WHERE a
a <=
<= pages
pages AND
AND pages
pages <=
<= b
b INTO
INTO c;
c;
SELECT count(isbn) FROM book WHERE a <= pages AND pages <= b INTO c;
END
END
END

You
You should
should notice
notice how
how the
the procedure
procedure stores
stores the
the result
result inc ccwith
withthe
theoperatator
operatatorINTO.
INTO.The
The
You
Youshould
shouldnotice
noticehow
howthe theprocedure
procedurestores
storesthe resultinin
theresult in c with
with the
the operatator
operatator INTO.
INTO. The
The
folowing
folowing
folowing shows
shows how
how the
the procedure
procedure can
can be
be used
used to
to calculates
calculates the
the number
number of
of books,
books, where
where
folowingshows
showshow
howthe
theprocedure
procedurecan
canbebeused
usedtotocalculates
calculatesthe thenumber
numberofofbooks,
books,where
where
the
the
the number
number
number of
of
of pages
pages
pages isis
is greater
greater
greater than
than
than oror
or equal
equal
equal to
to
to 200
200
200 and
and
and less
less
less than
than
than or
or
or equal
equal
equal to
to
to 500:
500:
500:
the number of pages is greater than or equal to 200 and less than or equal to 500:

183
183
183
183
JAVA 6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6:
JAVA 6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal examples
FInal examples

use
use books;
books;
set @num =
set @num = 0;
0;
call
call counter(200, 500,
counter(200, 500, @num);
@num);
select @num;
select @num;

ItItisisalso
alsopossible
possibletotodefine
definea aparameter
parameterasasINOUT.
INOUT.TheThefollowing
followingprocedure
proceduredetermines
determines
the
theaverage
averageofofnumber
numberofofpages
pagesininbooks
bookswhere
wherethe
thepage
pagenumber
numberisisless
lessthan
thanororequal
equaltoto
the
thevalue
the valueofof
value ofthe
theparameter
the parametert:t:
parameter t:

CREATE
CREATE DEFINER='pa'@'%'
DEFINER='pa'@'%' PROCEDURE
PROCEDURE 'average'(INOUT
'average'(INOUT t
t INT)
INT)
BEGIN
BEGIN
DECLARE
DECLARE ss int;
int;
DECLARE n
DECLARE n int;
int;
SELECT
SELECT SUM(pages), COUNT(*)
SUM(pages), COUNT(*) FROM
FROM book
book WHERE
WHERE pages
pages <=
<= t
t INTO
INTO s,
s, n;
n;
SET t
SET t =
= s
s /
/ n;
n;
END
END

and
and
andthe
theprocedure
procedurecan
canbebeused
usedasasfollows:
follows:

use books;
use books;
set
set @num
@num =
= 500;
500;
call average(@num);
call average(@num);
select
select @num;
@num;

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

184
184
184
184
JAVA
JAVA6: JDBC AND DATABASE APPLICATIONS Final examples
JAVA 6:
6: JDBC
JDBC AND
AND DATABASE
DATABASE APPLICATIONS
APPLICATIONS FInal
FInal examples
examples

The
Thefollowing script creates aadatabase with one table, that
thathas
hasonly
onlyone
onecolumn:
The following
following script
script creates
creates a database
database with
with one
one table,
table, that has only one column:
column:
use
use sys;
sys;
create
create database
database numbers;
numbers;
use numbers;
use numbers;
create
create table
table primes
primes (prime
(prime int
int primary
primary key);
key);

To
Tothis
To thisdatabase
this databaseI IIhave
database haveadded
have addedaaastored
added storedprocedure
stored procedurethat
procedure thatadds
that addsthe
adds thevalue
the valueofof
value ofaaaparameter
parameternn
parameter ntoto
to
the
the table, if n is a prime and not already is in the table. The result of
the table, if n is a prime and not already is in the table. The result of the procedure is
table, if n is a prime and not already is in the table. The result of the
the procedure
procedure isis
stored
stored in
stored in the
in the parameter
the parameter
parameter r. r.
r.
CREATE
CREATE DEFINER='pa'@'%'
DEFINER='pa'@'%' PROCEDURE
PROCEDURE 'isprime'(IN
'isprime'(IN n n int,
int, OUT
OUT r
r boolean)
boolean)
BEGIN
BEGIN
DECLARE
DECLARE c c int;
int;
SELECT
SELECT count(*) FROM
count(*) FROM primes
primes WHERE
WHERE prime
prime = = nn INTO
INTO c;c;
IF c > 0 THEN SET r
IF c > 0 THEN SET r = false; = false;
ELSEIF
ELSEIF n n = = 22 OR
OR nn == 33 OR
OR n
n == 5
5 OR
OR n
n == 7
7 THEN
THEN SET
SET rr =
= true;
true;
ELSEIF n < 11 OR mod(n, 2) = 0 THEN SET
ELSEIF n < 11 OR mod(n, 2) = 0 THEN SET r = false; r = false;
ELSE
ELSE
BEGIN
BEGIN
DECLARE
DECLARE t t int
int DEFAULT
DEFAULT 3; 3;
DECLARE
DECLARE m double DEFAULT
m double DEFAULT sqrt(n)
sqrt(n) + + 1;
1;
SET r =
SET r = true;true;
WHILE
WHILE t t <=
<= mm AND
AND r r == true
true DO
DO
IF
IF mod(n, t) = 0 THEN SET r
mod(n, t) = 0 THEN SET r =
= false;
false;
ELSE SET t =
ELSE SET t = t + 2; t + 2;
END
END IF;IF;
END
END WHILE;
WHILE;
END;
END;
END
END IF;
IF;
IF
IF r =
r = true
true THEN
THEN INSERT
INSERT INTO
INTO primes
primes VALUES
VALUES (n);
(n);
END IF;
END IF;
END
END

and
and below
andbelow an
belowan example
exampleofof
anexample ofanan application
applicationofof
anapplication the
ofthe procedure:
theprocedure:
procedure:
use
use numbers;
numbers;
set
set @res
@res =
= false;
false;
call
call isprime(31, @res);
isprime(31, @res);
select @res;
select @res;

The
The above procedure
aboveprocedure
Theabove does
proceduredoes not
doesnot have
nothave great
havegreat practical
greatpractical interest,
practicalinterest, and
interest,and the
andthe goal
goalisis
thegoal alone
isalone show
aloneshow that
showthat
that
in a stored
ininaastored procedure
storedprocedure you
procedureyou can
youcan use
canuse program
useprogram logic
programlogic in the
logicininthe same
thesame way
sameway as in for
wayasasininfor example
forexample Java.
exampleJava.
Java.

As
Asaaafinal
As final comment
finalcomment should
commentshould be
shouldbe added
beadded that
addedthat there
thereisis
thatthere much
ismuch more
moretoto
muchmore say
tosay about
sayabout stored
aboutstored procedures,
storedprocedures,
procedures,
and
andyou
and you
youmay may also
mayalso have
alsohave stored
havestored functions,
storedfunctions, but
functions,but
butthethe above
theabove should
aboveshould suffice
shouldsuffice to illustrate
sufficetotoillustrate what
whataaa
illustratewhat
stored procedure
procedureis.is.
storedprocedure
stored is.

185
185
185

Potrebbero piacerti anche