zetcode apache derby tutorial
TRANSCRIPT
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 1/68
ZetCode Apache Derby tutorial
This is Apache Derby tutorial. This tutorial will cover the Derby database engine, the SQL
understood by the Derby and programming Derby with the JDB A!".
Derby
Derby is a database engine written in Java language. "t has a relatively small #ootprint o# $%
&'B. "t wor(s in two modes. "n embedded or client%server mode.
Derby has roots in )**+ as JB'S. Later it was renamed to loudscape. "n )*** the company
developing loudscape was bought by "n#ormi, which was later ac-uired by "B'. "n $/
"B' contributed the code to the Apache So#tware 0oundation. The Derby pro1ect was born.
Sun 1oined the pro1ect and included the Derby in Java +. The pro1ect is rebranded as Java DB
in JD2.
Introduction to Derby
"n this chapter, we will cover the basic concepts and de#initions o# Derby. "t is necessary to
(now these basics because Derby is -uite involved. "t is not as simple as SQLite.
Derby is a relational database management system written in Java. "t implements an SQL%*$
core subset, as well as some SQL%** #eatures. "t uses "B' DB$ SQL synta. Derby has a
small #ootprint around $'B. "t has transaction support. The database #ormat used by Derby is
portable and plat#orm independent.
Deployment options
Derby can operate in two modes. 3mbedded or client%server. "n the embedded mode the
Derby engine runs within the Java 4irtual 'achine o# the application. The application is
accessing the database directly and eclusively. 5o other application can access the database
simultaneously. There is no need to set up a Derby server be#ore connecting to the database.
The Derby engine is started when we load the embedded driver. "n the client-server mode
Derby provides multi%user connectivity across a networ(. The Derby engine runs in the J4'
o# the server. 6ther applications can connect to the Database #rom di##erent J4's. 7e must
start a database server be#ore connecting to the database. This is similar to other 8DB'S li(e6racle or 'ySQL.
The Derby system
The Derby system consists o# an instance o# the Derby engine and its environment. "t
includes the system directory, the databases and the system%wide con#iguration. 3ach
database is located in a subdirectory o# the system directory having the same name as the
database. "n addition it has an error log #ile and an optional derby.properties #ile. Derby
writes in#ormation and error messages to a log #ile with a de#ault name derby.log. The
properties #ile contains con#iguration data, parameters speci#ic to the Derby system. Thederby system is not persistent. 7e must provide the location o# the system at every startup.
)
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 2/68
The Derby system is speci#ied with the derby.system.home property. "# the directory
speci#ied in the property does not eist, Derby creates it automatically. "# we do not speci#y
the property eplicitly, the current directory is used. The current directory is the value o# the
J4' user.dir property. "t is recommended to always speci#y the derby.system.home eplicitly.
-Dderby.system.home=/home/janbodnar/programming/derby/dbs
An eample o# how we set the property. "t can be set on the command line, in a dialog bo in
case we use an "D3 or in the derby.properties #ile.
The Derby properties
The derby.properties is a con#iguration #ile #or the Derby system. "t is a simple tet #ile
which enables us to con#igure the entire Derby system, a speci#ic database or a conglomerate.
A conglomerate is a table or inde in Derby. 7e can con#igure several options. 7hether to
authori9e users or not. 7hich databases to boot. :ow to name the error log #ile. The location
o# the system directory and many more. The derby.properties is not created automatically.
7e must create the #ile ourselves i# we want to use it.
Starting & ending Derby database
"n the embedded mode, the database is started when an application #irst ma(es a connection
to it. "t is possible to con#igure the Derby system to boot all available databaises when it starts
with the derby.system.bootAll property. 7hen the database has started, a message is
written to the derby.log #ile. A database is shut down by speci#ying the shutdown=true
attribute in the connection ;8L. 7e can shutdown a database or an entire Derby system.
DriverManager.getConnection("jdbcderbytestdb!shutdown=true"!DriverManager.getConnection("jdbcderby!shutdown=true"!
The #irst JDB call shuts down the testdb database. The second call ends the whole Derby
system. 5ote, that na SQL3pection is raised when a system shuts down. This eception
should be programmatically handled. 7e should also close all eisting resources be#ore
shutting down the database or the system.
"n the client%server mode, the Derby server is started with the start5etwor(Server script and
ended with the stop5etwor(Server script. They are located in the bin subdirectory o# theinstallation directory.
The jar files
"nside the lib subdirectory o# the installation directory, we can #ind several libraries. 3ach o#
the 1ar #iles serves a speci#ic #unction. The derby.1ar is a library used #or embedded databases.
7e need to have this 1ar #ile in our classpath in embedded applications. "n client%server mode,
this library must be on the server. The derbynet.1ar is used to start the Derby 5etwor( Server.
The derbyclient.1ar is used by clients connecting to the Derby 5etwor( Server. The
derbytools.1ar is used with Derby tools. The derbyrun.1ar #ile is a special 1ar #ile that
simpli#ies how we invo(e the Derby tools and the 5etwor( Server. 0inally, there are some
$
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 3/68
locale libraries. They are used to provide translated messages. 0or eample, the
derbyLocale<cs.1ar provides 9ech messages.
The Derby schema
"n database theory, a schema is a structure o# a database. "t is described in a #ormal language=SQL>. "t re#ers to the organi9ation o# data. The #ormal de#inition o# a database schema is a
set o# #ormulas called integrity constraints imposed on a database. =7i(ipedia>
"n Derby, a database schema has a narrower meaning. "t is a container which is used to
logically group ob1ects. "t is similar to Java pac(ages or ?? namespaces. A Derby database
may have multiple schemas. 7e can create two tables with the same names provided that
they are placed in two di##erent schemas. Derby de#ault schema is A!!. "# we do not provide
any schema, a database ob1ect is assigned to this de#ault schema.
A schema is created in Derby with C#$A%$ 'C$MA statement. "# we connect to a database,
the user name that we have provided in the connection ;8L becomes the current schema o#
the connection. All database ob1ects will be created within this schema. The current schema
can be changed with the '$% 'C$MA statement. There is another built%in schema called S@S
which is used to isolate system tables.
Derby has a tool called dbloo( which dumps a database and its schemas. The output o# the
tool is the #ormal description o# the database in DDL =data de#inition language>.
The connection URL
A#ter the driver is loaded, a connection to the database is created. A connection is a sessionwith a database. At the end o# the wor(, the connection to the database is closed. To establish
a connection, we call the getConnection( method o# the DriverManager class.
The connection ;8L speci#ies the characteristics o# a connection.
jdbcderby)subsubprotocol*)database+ame*)!attribute=value*,
The above is a synta #or a Derby database connection ;8L. The de#ault subprotocol is
directory and it is o#ten omitted. 7e can wor( with databases only in memory when we
speci#y the memory subprotocol. The database5ame is the name o# the database that we
want to create andor connect to.
7e can use several attributes in the connection ;8L. 7e can use attributes to create a
database, to connect to a secured database with a user name and a password. 0urther we use
the connection attributes to shut down a database or a Derby system, to encrypt data or to
restore a database #rom a bac(up.
jdbcderbytestdbjdbcderby//localhost0/testdb
7e use di##erent connection strings to connect to a embedded and to client%server Derby
system. The #irst connection string connects to an embedded database the second one to theclient%server database. The de#ault port #or Derby is )C$.
&
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 4/68
jdbcderbytestdb!create=truejdbcderbytestdb!shutdown=truejdbcderbymemorytestdb
7e have another three connection strings. The #irst connection string creates the testdb
database. The second one shuts down the testdb database. The third one connects to a testdb
created in memory.
SQL files
"n the #ollowing two SQL #iles, cars.s-l and authors<boo(s.s-l, we create three tables which
we will use throughout this tutorial.
1 cat cars.s2l'$% 'C$MA 3'$#!C#$A%$ %A45$ CA#'(6D 6+% 7#6MA#8 9$8: +AM$ ;A#CA#(<: 7#6C$ 6+%!6+'$#% 6+%> CA#' ;A53$'(: ?Audi?: @!
6+'$#% 6+%> CA#' ;A53$'(: ?Mercedes?: 00!6+'$#% 6+%> CA#' ;A53$'(<: ?'Boda?: !6+'$#% 6+%> CA#' ;A53$'(: ?;olvo?: !6+'$#% 6+%> CA#' ;A53$'(: ?4entley?: <!6+'$#% 6+%> CA#' ;A53$'(@: ?Citroen?: !6+'$#% 6+%> CA#' ;A53$'(0: ?ummer?: !6+'$#% 6+%> CA#' ;A53$'(: ?;olBswagen?: @!
The cars.s-l #ile creates the A8S table.
1 cat authorsEbooBs.s2l'$% 'C$MA 3'$#!
C#$A%$ %A45$ A3%>#'(6D 6+% 7#6MA#8 9$8: +AM$ ;A#CA#(!C#$A%$ %A45$ 4>>9'(6D 6+% 7#6MA#8 9$8: A3%>#E6D 6+%: %6%5$ ;A#CA#(:
F>#$6G+ 9$8(A3%>#E6D #$F$#$+C$' A3%>#'(6D!
6+'$#% 6+%> A3%>#'(6D: +AM$ ;A53$'(: ?HacB 5ondon?!6+'$#% 6+%> A3%>#'(6D: +AM$ ;A53$'(: ?onore de 4alIac?!6+'$#% 6+%> A3%>#'(6D: +AM$ ;A53$'(<: ?5ion Feuchtwanger?!6+'$#% 6+%> A3%>#'(6D: +AM$ ;A53$'(: ?$mile Jola?!6+'$#% 6+%> A3%>#'(6D: +AM$ ;A53$'(: ?%ruman Capote?!
6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: : ?Call oK the Lild?!6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: : ?Martin $den?!
6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(<: : ?>ld Goriot?!6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: : ?Cousin 4ette?!6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: <: ?Hew 'uess?!6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(@: : ?+ana?!6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(0: : ?%he 4elly oK 7aris?!6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: : ?6n Cold blood?!6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: : ?4reaBKast at%iKKany?!
The authors<boo(s.s-l #ile creates two tables. A;T:68S and B662S.
/
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 5/68
Sources
The #ollowing materials were used to create this tutorial. Derby DeveloperEs Fuide, Derby
Server and Administration Fuide, Fetting Started with Derby, Derby Tools and ;tilities
Fuide and Derby 8e#erence 'anual.
"n the chapter, we have introduced the basic concepts o# the Derby database.
Installation & configuration of Derby
"n the #ollowing pages, we will show how to install Derby and will con#igure Derby to our
needs.
7e download the latest version o# Derby #rom db.apache.orgderby. 7e create an
installation directory and unpac( the compressed #iles to this directory.
1 lsbin docs javadoc lib +>%6C$ testdemo inde.html 9$8' 56C$+'$ #$5$A'$-+>%$'.html
7e list the contents o# the installation directory. "n the bin subdirectory, we have several
Derby tools. The docs directory provides documentation #or Derby. "n :T'L and !D0
#ormat. The documentation is very good and we highly recommend to have a loo( at these
#iles. "n the lib subdirectory there are various JA8 #iles needed #or wor(ing with Derby.
The Java D
Derby is included in the JD2 since Java +. Java DB is a supported version o# Apache Derby
and contains the same binaries as Apache Derby.
1 ls [email protected]</db<#D7A#%8 demo inde.html lib +>%6C$ #$5$A'$-+>%$'.htmlbin docs javadoc 56C$+'$ register.html
"n the JD2 installation directory, we have a subdirectory called db, where we #ind the Java
DB #iles.
"n the 6verview section o# the release notes we read the #ollowing
Derby is a pure Java relational database engine using standard SQL and JDB as its A!"s.
Derby #unctionality includes
• 3mbedded engine with JDB drivers
• 5etwor( Server
• 5etwor( client JDB drivers
• ommand line tools i1 =SQL scripting>, dbloo( =schema dump> and sysin#o =system
in#o>
C
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 6/68
!nvironment variables
Setting environment variables is optional. ;sing environment variables will ma(e the li#e
easier #or us.
1 eport D$#48E>M$=N/bin/derby1 eport 7A%=17A%N/bin/derby/bin1 eport D$#48E>M$=-Dderby.system.home=/home/janbodnar/programming/derby/dbs
7e set a D38B@<:6'3 variable to the Derby installation directory. Some tools may use
this variable. Then we add a bin subdirectory to the !AT: variable. This way we do not have
to #ully speci#y the path to the Derby tools. "n the D38B@<6!TS environment variable we
can set various Derby or Java related options. 0or eample, we set the derby.system.home
property.
1 java -jar 1D$#48E>M$/lib/derbyrun.jar sysinKo------------------ Hava 6nKormation ------------------Hava ;ersion [email protected]<Hava ;endor 'un Microsystems 6nc.Hava home /home/janbodnar/bin/[email protected]</jreHava classpath /home/janbodnar/bin/derby/lib/derbyrun.jar>' name 5inu>' architecture i<@...
7e use the derbyrun.1ar #ile to eecute the sysin#o tool to get some in#o about the Java and
Derby.
"reating a database
Derby does not have a C#$A%$ DA%A4A'$ statement li(e 'ySQL or 6racle. 7e have to
create a database by creating a connection and setting a connection property createGtrue.
1 java -Dderby.system.home=/home/janbodnar/programming/derby/dbs OP -jar 1D$#48E>M$/lib/derbyrun.jar ij
ij version .ijP
7e start the i1 tool with the derbyrun.1ar #ile. 7e set the derby system directory. "t is thedirectory, where we create databases and where log #ile is created.
ijP connect ?jdbcderbytmpdb!user=tmpuser!create=true?!
A database tmpdb is created inside the Derby system directory and we also connect to it. The
connection is created in the embedded mode.
ijP C#$A%$ %A45$ F#6$+D'(6D 6+% 7#6MA#8 9$8: +AM$ ;A#CA#(! rows inserted/updated/deletedijP 6+'$#% 6+%> F#6$+D'(6D: +AM$ ;A53$'(: ?Hane?! row inserted/updated/deletedijP 6+'$#% 6+%> F#6$+D'(6D: +AM$ ;A53$'(: ?%homas?! row inserted/updated/deleted
+
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 7/68
ijP 6+'$#% 6+%> F#6$+D'(6D: +AM$ ;A53$'(<: ?4eBy?! row inserted/updated/deleted
7e create a 08"35DS table and add three rows to it.
ijP '$5$C% , F#>M F#6$+D'!6D Q+AM$------------------------------------- QHane Q%homas< Q4eBy
< rows selected
7e chec( the data.
ijP '>L %A45$' 6+ %M73'$#!%A45$E'C$M Q%A45$E+AM$ Q#$MA#9'
------------------------------------------------------------------------%M73'$# QF#6$+D' Q
row selected
7hen we created a connection, we have speci#ied a user name. The user name is the database
schema, in which the 08"35DS table is created.
ijP D6'C>++$C%!ijP '>L C>++$C%6>+'!+o connections available.ijP $R6%!
1
7e disconnect #rom the tmpdb database. The '>L C>++$C%6>+' statement in#orms that
there are no open connections. 7e eit the i1 tool with the 3H"T command.
1 rm -rK dbs/tmpdb
7e delete the database #rom the Derby system. Derby has no D#>7 DA%A4A'$ statement.
This is the end o# the Derby tutorial chapter, in which we have installed and con#igured
Derby.
Derby tools
"n this chapter, we will mention Derby tools. The Derby tools and utilities are a set o# scripts
supplied with Derby. They are typically used to create, inspect, and update a Derby database.
"n this page, we will mention the sysin#o, the dbloo(, the i1, the start5etwor(Server and the
stop5etwor(Server tools. 5ote that these tools have .bat etension on 7indows.
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 8/68
Launching Derby tools
Derby tools can be run in two ways. 7e use the script names located in the bin directory o#
the Derby installation directory. 6r we can use the derbyrun.1ar #ile to launch them.
1 ij1 java -jar 1D$#48E>M$/lib/derbyrun.jar ij
Assuming that the Derby bin directory is added to the !AT: environment variable, we can
launch the i1 tool by speci#ying the name o# the script in the terminal. The second line runs
the i1 using the derbyrun.1ar #ile.
sysinfo
The sysinfo tool provides in#ormation about the 6perating system, Java and Derby. "t will
print among others Java version, Java home directory, 6S version, Java runtime version,
Derby version, current and supported locales. The tool can be use#ul to trac( down someinstallation or con#iguration issues with Derby.
1 sysinKo------------------ Hava 6nKormation ------------------Hava ;ersion [email protected]<Hava ;endor 'un Microsystems 6nc.Hava home /home/janbodnar/bin/[email protected]</jreHava classpath/home/janbodnar/bin/derby/lib/derby.jar/home/janbodnar/bin/derby/lib/ derbynet.jar/home/janbodnar/bin/derby/lib/derbytools.jar/home/janbodnar/b
in/ derby/lib/derbyclient.jar>' name 5inu>' architecture i<@>' version <..--genericHava user name janbodnarHava user home /home/janbodnar...
This is an ecerpt #rom the in#ormation provided on a particular system.
ij
The ij is an interactive scripting tool. "t is used #or running scripts or interactive -ueries
against a Derby database.
1 cat cars.s2lC#$A%$ 'C$MA 3'$#!C#$A%$ %A45$ CA#'(6D 6+% 7#6MA#8 9$8: +AM$ ;A#CA#(<: 7#6C$ 6+%!6+'$#% 6+%> CA#' ;A53$'(: ?Audi?: @!6+'$#% 6+%> CA#' ;A53$'(: ?Mercedes?: 00!6+'$#% 6+%> CA#' ;A53$'(<: ?'Boda?: !6+'$#% 6+%> CA#' ;A53$'(: ?;olvo?: !6+'$#% 6+%> CA#' ;A53$'(: ?4entley?: <!
6+'$#% 6+%> CA#' ;A53$'(@: ?Citroen?: !6+'$#% 6+%> CA#' ;A53$'(0: ?ummer?: !6+'$#% 6+%> CA#' ;A53$'(: ?;olBswagen?: @!
I
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 9/68
7e have a cars.s-l #ile which creates a database schema and a A8S table.
1 ijij version .ijP connect ?jdbcderbydbs/testdb!user=user!create=true?!
7e start the i1 tool. "# we had not added the DerbyEs bin directory to the !AT: variable, we
would have to speci#y the whole path to the i1 tool. 7e create a testdb database in the dbs
directory and ma(e a connection to it. The dbs directory is a subdirectory o# our current
directory, where the i1 was launched.
ijP '>L C>++$C%6>+'!C>++$C%6>+, - jdbcderbydbs/testdb, = current connection
The '>L C>++$C%6>+' statement displays opened connections to Derby databases.
ijP #3+ ?cars.s2l?!ijP C#$A%$ 'C$MA 3'$#! rows inserted/updated/deletedijP C#$A%$ %A45$ CA#'(6D 6+% 7#6MA#8 9$8: +AM$ ;A#CA#(<: 7#6C$ 6+%! rows inserted/updated/deletedijP 6+'$#% 6+%> CA#' ;A53$'(: ?Audi?: @! row inserted/updated/deletedijP 6+'$#% 6+%> CA#' ;A53$'(: ?Mercedes?: 00! row inserted/updated/deletedijP 6+'$#% 6+%> CA#' ;A53$'(<: ?'Boda?: !...
7e load and eecute the cars.s-l site. 7e are in#ormed about the ongoing operations.
ijP '$5$C% , F#>M CA#'!6D Q+AM$ Q7#6C$------------------------------------------------------ QAudi Q@ QMercedes Q00< Q'Boda Q Q;olvo Q Q4entley Q<@ QCitroen Q0 Qummer Q Q;olBswagen Q@
rows selected
7e select all rows #rom the A8S table.
ijP connect ?jdbcderbydbs/testdb!shutdown=true?!$##># @ Database ?dbs/testdb? shutdown.
Shutting down a database in Derby results in an eception. The 38868 I+ is epected.
ijP '>L C>++$C%6>+'!+o current connection
The connection is closed.
*
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 10/68
ijP $R6%!
7e -uit the i1 tool with the 3H"T command. 5ote that each command is #ollowed by
semicolon.
dbloo#
The dblook tool is used to save the data de#inition language o# database ob1ects including
tables, views, indees or triggers.
1 dblooB -d jdbcderbydbs/testdb-- %imestamp -- <<<<.@00-- 'ource database is dbs/testdb-- Connection 3#5 is jdbcderbydbs/testdb-- append5ogs Kalse
-- ----------------------------------------------
-- DD5 'tatements Kor schemas-- ----------------------------------------------
C#$A%$ 'C$MA "3'$#"!
-- ------------------------------------------------ DD5 'tatements Kor tables-- ----------------------------------------------
C#$A%$ %A45$ "3'$#"."CA#'" ("6D" 6+%$G$# +>% +355:"+AM$" ;A#CA#(<: "7#6C$" 6+%$G$#!
-- ----------------------------------------------
-- DD5 'tatements Kor Beys-- ----------------------------------------------
-- primary/uni2ueA5%$# %A45$ "3'$#"."CA#'" ADD C>+'%#A6+% "'S5<<0" 7#6MA#8 9$8("6D"!
"n the above eample, we have dumped the ob1ects #rom the testdb database. 7ith the %d
option we have provided the connection ;8L to the database. "n our case the dbloo( tool
saved a database schema and one table. 7ith the %o option the output can be redirected to a
#ile.
start$et%or#Server & stop$et%or#Server
The two scripts start and stop the Derby 5etwor( server. "n case o# a networ(ed server,
multiple connections to a Derby database may be created.
1 start+etworB'erver T)* <01 'un Feb < C$% 'ecurity manager installed usingthe 4asic server security policy.'un Feb < C$% Apache Derby +etworB 'erver - ... -( started and ready to accept connections on port 0
:ere we start the Derby 5etwor( Server with the start5etwor(Server script.
)
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 11/68
ijP connect ?jdbcderby//localhost0/dbs/testdb?!
:ere we connect to the testdb database via the Derby 5etwor( Server. The connection ;8L
is di##erent #or networ(ed connections.
ijP '$5$C% , F#>M 3'$#.CA#'!6D Q+AM$ Q7#6C$------------------------------------------------------ QAudi Q@ QMercedes Q00< Q'Boda Q Q;olvo Q Q4entley Q<@ QCitroen Q0 Qummer Q Q;olBswagen Q@
rows selected
7e select all cars #rom the A8S table. Since we have not provided the database schema in
the connection ;8L, we must speci#y it now. The database schema is the user name in our
case ;S38)$.
1 stop+etworB'erver'un Feb C$% Apache Derby +etworB 'erver- ... - ( shutdown1 'un Feb C$% Apache Derby +etworB 'erver- ... - ( shutdown
7e have stopped the server with the stop5etwor(Server script.
"n the chapter, we have written about Derby tools.
he ij tool
"n the #ourth chapter, we are going to loo( at DerbyEs i1 tool in a greater detail.
The i1 is an interactive scripting tool supplied with Derby. "t is a command line client #or the
Derby database system. "t can be used in two ways. 3ither run SQL #iles or interactively
eecute SQL statements. The i1 is located in the bin directory o# the Derby installation
directory.
1 ls 1D$#48E>M$/bin Q grep ijijij.bat
There are two scripts. The one with the .bat etension is #or 7indows.
Starting ij
The i1 can be started in three basic ways.
1 ij
))
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 12/68
ij version .ijP
Derby i1 can be started with the i1 script. The above eample assumes that we have the
DerbyEs bin directory in our !AT: variable. 6therwise we must use the #ull path to the i1
tool.
1 java -cp 1D$#48E>M$/lib/derbytools.jar org.apache.derby.tools.ijij version .ijP
Another way is to eecute the compiled Java program. 7e must have the derbytools.1ar in
our classpath. The #irst way does essentially the same within the script #ile. "t also wor(s with
environment variables.
1 java -jar 1D$#48E>M$/lib/derbyrun.jar ijij version .
ijP
"n the third way, we use the derbyrun.1ar #ile to start the i1 tool.
Running SQL scripts
;nli(e 'ySQL or !ostgreSQL command line tools, i1 is very simplistic. "t does not have a
history o# commands. ursor (eys cannot be used. "t is -uite unconvenient to use the tool. "t
is easier to edit SQL statements in a #ile and run it with the i1 tool.
1 cat cars.s2l
'$% 'C$MA 3'$#!C#$A%$ %A45$ CA#'(6D 6+% 7#6MA#8 9$8: +AM$ ;A#CA#(<: 7#6C$ 6+%!6+'$#% 6+%> CA#' ;A53$'(: ?Audi?: @!6+'$#% 6+%> CA#' ;A53$'(: ?Mercedes?: 00!6+'$#% 6+%> CA#' ;A53$'(<: ?'Boda?: !6+'$#% 6+%> CA#' ;A53$'(: ?;olvo?: !6+'$#% 6+%> CA#' ;A53$'(: ?4entley?: <!6+'$#% 6+%> CA#' ;A53$'(@: ?Citroen?: !6+'$#% 6+%> CA#' ;A53$'(0: ?ummer?: !6+'$#% 6+%> CA#' ;A53$'(: ?;olBswagen?: @!
A A8S table is created in schema ;S38)$ and #ive rows are inserted.
ijP #3+ ?cars.s2l?!ijP '$% 'C$MA 3'$#! rows inserted/updated/deletedijP C#$A%$ %A45$ CA#'(6D 6+% 7#6MA#8 9$8: +AM$ ;A#CA#(<: 7#6C$ 6+%! rows inserted/updated/deletedijP 6+'$#% 6+%> CA#' ;A53$'(: ?Audi?: @! row inserted/updated/deleted...
7e use the 8;5 command to eecute the cars.s-l #ile. The #ile is located in the same
directory, where i1 was launched.
ijP '$5$C% , F#>M CA#'!6D Q+AM$ Q7#6C$
)$
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 13/68
------------------------------------------------------ QAudi Q@ QMercedes Q00< Q'Boda Q Q;olvo Q Q4entley Q<
@ QCitroen Q0 Qummer Q Q;olBswagen Q@
rows selected
7e chec( the data. The table was success#ully created.
An SQL #ile name can be ta(en by the i1 tool as a parameter.
1 cat cars.s2l
C>++$C% ?jdbcderbytestdb?!
'$% 'C$MA 3'$#!C#$A%$ %A45$ CA#'(6D 6+% 7#6MA#8 9$8: +AM$ ;A#CA#(<: 7#6C$ 6+%!6+'$#% 6+%> CA#' ;A53$'(: ?Audi?: @!6+'$#% 6+%> CA#' ;A53$'(: ?Mercedes?: 00!6+'$#% 6+%> CA#' ;A53$'(<: ?'Boda?: !6+'$#% 6+%> CA#' ;A53$'(: ?;olvo?: !6+'$#% 6+%> CA#' ;A53$'(: ?4entley?: <!6+'$#% 6+%> CA#' ;A53$'(@: ?Citroen?: !6+'$#% 6+%> CA#' ;A53$'(0: ?ummer?: !6+'$#% 6+%> CA#' ;A53$'(: ?;olBswagen?: @!
7e add a 6553T statement to the cars$.s-l #ile. 7hen we launch the i1 tool, we are not
yet connected to the database.
ijP D#>7 %A45$ CA#'! rows inserted/updated/deletedijP $R6%!1
7e drop the table be#ore we eecute the cars$.s-l script.
1 java -Dderby.system.home=/home/janbodnar/programming/derby/dbs O
P -jar 1D$#48E>M$/lib/derbyrun.jar ij cars.s2l
7e set the Derby system directory and launch the i1 tool with the cars$.s-l as a parameter.
The A8S table is created again.
asic commands
7e can issue two (inds o# commands. ommands speci#ic to the i1 tool and SQL statements.
3ach command in i1 is terminated with a semicolon. All i1 commands, identi#iers, and
(eywords are case%insensitive.
ijP $57!
)&
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 14/68
'upported commands include 7#>%>C>5 ?HD4C protocol? ) A' ident *!
-- sets a deKault or named protocol D#6;$# ?class Kor driver?! -- loads the named class C>++$C% ?url Kor database? ) 7#>%>C>5 named7rotocol * ) A' connection+ame
*! -- connects to database 3#5 -- and may assign identiKier...
The :3L! command shows a list o# i1 commands
ijP C>++$C% ?jdbcderbytestdb?!
The 6553T command connects to a database. "n our case the database name is testdb.
This eample assumes that we have set the Derby system directory. ='ore about it in the net
section.> Derby by de#ault does not re-uire a user name and a password. 7e can con#igure
Derby to re-uire it.
ijP '>L C>++$C%6>+'!C>++$C%6>+, - jdbcderbytestdb, = current connection
The '>L C>++$C%6>+' statement lists all opened connections. "n our case we can see an
opened connection to the testdb database.
ijP '>L %A45$'!%A45$E'C$M Q%A45$E+AM$ Q#$MA#9'
------------------------------------------------------------------------'8' Q'8'A56A'$' Q'8' Q'8'C$C9' Q'8' Q'8'C>57$#M' Q...
The '>L %A45$' command shows all tables in a database. There are a #ew S@S tables.
ijP '>L %A45$' 6+ 3'$#!%A45$E'C$M Q%A45$E+AM$ Q#$MA#9'------------------------------------------------------------------------3'$# QCA#' Q
row selected
7e can list tables in a speci#ic schema. The '>L %A45$' 6+ 3'$# shows tables in the
;S38)$ schema.
ijP D$'C#64$ 3'$#.CA#'!C>53M+E+AM$ Q%87$E+AM$QD$CTQ+3MTQC>53MTQC>53M+ED$FQCA#E>C%$TQ6'E+355T------------------------------------------------------------------------------6D Q6+%$G$# Q Q Q Q+355 Q+355 Q+>+AM$ Q;A#CA# Q+355Q+355Q< Q+355 Q@ Q8$'
7#6C$ Q6+%$G$# Q Q Q Q+355 Q+355 Q8$'
)/
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 15/68
< rows selected
The D3S8"B3 command provides a decription o# the speci#ied table or view. "# the
;S38)$ schema is not the current schema o# the connection, we have to speci#y it be#ore the
table name. The current schema is speci#ied in the connection string as the user name.
ijP D6'C>++$C%!ijP '>L C>++$C%6>+'!+o connections available.
The D"S6553T command disconnects #rom the database. The subse-uent S:67
6553T"65S command shows no available connections.
ijP $R6%!1
0inally, we eit the i1 tool. "n case o# an embedded environment, it also shuts down the
database. 7hich is e-uivalent to the 6553T E1dbcderbytestdbshutdownGtrueEcommand.
The main purpose o# the i1 tool is to issue SQL commands. 7e reconnect to the testdb
database.
1 ijij version .ijP C>++$C% ?jdbcderbytestdb!user=3'$#?!
5ow the current schema is the ;S38)$ schema. 7hen issuing SQL statements #or tableslocated in the ;S38)$ schema, we can omit the schema name.
ijP '$5$C% , F#>M CA#' L$#$ 6D 6+ (: <: !6D Q+AM$ Q7#6C$------------------------------------------------------ QAudi Q@< Q'Boda Q Q4entley Q<
< rows selected
"n the above SQL statement, we select all three columns #or rows with "Ds ), & and C.
ijP '$5$C% , F#>M A77.F#6$+D'!6D Q+AM$------------------------------------- QHane Q%homas< Q4eBa
< rows selected
Three rows #rom the 08"35DS table were selected. Since the table is not located in the
current schema, we must #ully -uali#y the table name.
)C
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 16/68
ijP 6+'$#% 6+%> A77.F#6$+D'(6D: +AM$ ;A53$'(: ?#obert?! row inserted/updated/deletedijP '$5$C% 6D: +AM$ F#>M A77.F#6$+D' L$#$ 6D=!6D Q+AM$------------------------------------- Q#obert
row selected
7e insert a new row into the 08"35DS table and later select it.
Specifying the Derby system directory
3ach time we wor( with Derby, we have to provide the Derby system directory. "n this
directory we can #ind our database #iles, con#iguration data or a log #ile. "# we do not provide
a Derby system directory a current directory is assumed to be the Derby system one. To
provide the Derby system directory, we assign the derby.system.home property. "t can be
done via J4' option, con#iguration #ile, environment variable or in a Java #ile.
1 lscars.s2l dbs docN ij.properties linBscars.s2lN doc dump lib
The current wor(ing directory has a subdirectory called dbs. 7e want this directory to be our
Derby system directory. The current wor(ing directory is the place #rom where we launch the
i1 tool.
1 java -Dderby.system.home=/home/janbodnar/programming/derby/dbs OP -jar 1D$#48E>M$/lib/derbyrun.jar ijij version .
:ere we speci#y the Derby system directory with the %D J4' option. The derby.log #ile is
created in the system directory. "n our case the log #ile should appear in the dbs directory.
The derby.log #ile is recreated each time we connect to a Derby database. 7e can loo( at the
timestamp. "# the derby.log #ile appears ouside the intended directory, we have not set the
Derby system directory correctly.
ijP C>++$C% ?jdbcderbytestdb?!ijP '>L C>++$C%6>+'!C>++$C%6>+, - jdbcderbytestdb
, = current connection
Since we have correctly set the Derby system directory, we only speci#y the database name in
the connection ;8L and omit the #ull path. The '>L C>++$C%6>+' shows the opened
connection.
7e might not want to speci#y the Derby system directory each time. 7e could utili9e the
D38B@<6!TS environment variable.
1 echo 1D$#48E>7%'
-Dderby.system.home=/home/janbodnar/programming/derby/dbs
)+
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 17/68
1 ijij version .ijP C>++$C% ?jdbcderbytestdb?!ijP '>L C>++$C%6>+'!C>++$C%6>+, - jdbcderbytestdb, = current connection
reating a connection to a Derby database is now a bit easier. 7e save a #ew (ey stro(es.
The ij properties
7hen starting up the i1 tool, we can speci#y properties on the command line or in a properties
#ile. The properties are various parameters ta(en by the i1 tool. They can save us some
repetitive wor(.
1 java -Dij.user=3'$# -Dij.database=testdb -Dij.protocol=jdbcderby OP -Dderby.system.home=/home/janbodnar/programming/derby/dbs O
P -jar 1D$#48E>M$/lib/derbyrun.jar ijij version .C>++$C%6>+, - jdbcderbytestdb, = current connectionijP '$5$C% , F#>M CA#' L$#$ 6D = !6D Q+AM$ Q7#6C$------------------------------------------------------ QAudi Q@
row selectedijP
7e provide three i1 properties on the command line with the %D option. The i1.user speci#ies
the user name to establish a connection. The supplied user name becomes the current schema.
The i1.database has the database name to which we connect. The i1.protocol property speci#ies
the de#ault protocol and subprotocol portions o# the database connection ;8L. 7e are ready
to launch SQL statements.
"n the net eample, we create an i1.properties #ile, where we set three i1 properties.
1 cat ij.propertiesij.user=3'$#ij.database=testdb
ij.protocol=jdbcderby
7ith the cat command, we show the contents o# the i1.properties #ile. 7e set the same
properties as in the #irst eample.
1 java -Dderby.system.home=/home/janbodnar/programming/derby/dbs OP -jar 1D$#48E>M$/lib/derbyrun.jar ij -p ij.propertiesij version .C>++$C%6>+, - jdbcderbytestdb, = current connectionijP '$5$C% , F#>M CA#' L$#$ 6D=!6D Q+AM$ Q7#6C$
------------------------------------------------------ QMercedes Q00
)
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 18/68
row selected
The %p option o# the i1 tool ta(es the properties #ile name.
"n the chapter, we have covered the i1 tool.
!"#
"n the #ollowing pages, we will wor( with the SQL understood by the Derby database engine.
7e will not go into much detail about the SQL language. This chapter is a -uic( recap o# the
most important SQL statements present in the Derby database.
!"# $!tructured "uery #anguage% is a database computer language designed #or
managing data in relational database management systems. Derby supports only a limited set
o# SQL statements. Some important statements (nown #rom other database systems are
missing. Derby implements an SQL%*$ core subset, as well as some SQL%** #eatures.
ijP D#>7 %A45$ A3%>#'! rows inserted/updated/deletedijP D#>7 %A45$ 4>>9'! rows inserted/updated/deleted
7e have previously created the A;T:68S and B662S tables. 7e are going to recreate
them. The D86! TABL3 SQL statement drops the table #rom the database. 5ote that the
D86! TABL3 "0 3H"STS statement does not eist in Derby.
ijP C#$A%$ %A45$ A3%>#'(6D 6+% 7#6MA#8 9$8: +AM$ ;A#CA#(! rows inserted/updated/deleted
The 83AT3 TABL3 statement creates a new table. "t has two columns, "D and 5A'3. "n
the "D column we will place integers, in the 5A'3 column strings with up to $C characters.
A !8"'A8@ 23@ uni-uely identi#ies each record in the table. 3ach author is a uni-ue
personality. 3ven i# there are authors with the same name, each o# them is in a separate row
in the A;T:68S table. 6nly one column in a table can have this constraint.
ijP C#$A%$ %A45$ 4>>9'(6D 6+% 7#6MA#8 9$8: A3%>#E6D 6+%:P %6%5$ ;A#CA#(: F>#$6G+ 9$8(A3%>#E6D #$F$#$+C$' A3%>#'(6D! rows inserted/updated/deleted
7e create a B662S table, which has three columns. The 0683"F5 23@ speci#ies that the
values in the A;T:68<"D column must match the values in the "D column o# the
A;T:68S table. 0oreign (eys provide a way to en#orce the re#erential integrity o# a
database. 3ach boo( was written by one or more authors. So in the B662S table #or the
A;T:68<"D column we can have only values that are present in the A;T:68S table.
ijP 6+'$#% 6+%> A3%>#'(6D: +AM$ ;A53$'(: ?HacB 5ondon?!ijP 6+'$#% 6+%> A3%>#'(6D: +AM$ ;A53$'(: ?onore de 4alIac?!ijP 6+'$#% 6+%> A3%>#'(6D: +AM$ ;A53$'(<: ?5ion Feuchtwanger?!ijP 6+'$#% 6+%> A3%>#'(6D: +AM$ ;A53$'(: ?$mile Jola?!ijP 6+'$#% 6+%> A3%>#'(6D: +AM$ ;A53$'(: ?%ruman Capote?!
7e add #ive rows to the A;T:68S table using the "5S38T "5T6 SQL statement.
)I
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 19/68
ijP 6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: : ?Call oK theLild?!ijP 6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: : ?Martin $den?!ijP 6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(<: : ?>ld Goriot?!ijP 6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: : ?Cousin 4ette?!ijP 6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: <: ?Hew 'uess?!
ijP 6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(@: : ?+ana?!ijP 6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(0: : ?%he 4elly oK7aris?!ijP 6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: : ?6n Cold blood?!ijP 6+'$#% 6+%> 4>>9'(6D: A3%>#E6D: %6%5$ ;A53$'(: : ?4reaBKast at%iKKany?!
7e insert I rows into the B662S table.
ijP '$5$C% +AM$: %6%5$ F#>M A3%>#': 4>>9'P L$#$ A3%>#'.6D = 4>>9'.A3%>#E6D!+AM$ Q%6%5$-------------------------------------------------HacB 5ondon QCall oK the LildHacB 5ondon QMartin $denonore de 4alIac Q>ld Goriotonore de 4alIac QCousin 4ette5ion Feuchtwanger QHew 'uess$mile Jola Q+ana$mile Jola Q%he 4elly oK 7aris%ruman Capote Q6n Cold blood%ruman Capote Q4reaBKast at %iKKany
rows selected
The above SQL -uery 1oins the two tables. "t assigns each boo( title to an author.
utoincrement
Derby allows to create an autoincrement column. The value o# an autoincrement column
increments automatically with every "5S38T.
C#$A%$ %A45$ F#6$+D'(6D 6+% 7#6MA#8 9$8 G$+$#A%$D A5LA8' A' 6D$+%6%8 ('%A#% L6% : 6+C#$M$+% 48 :
+AM$ ;A#CA#(!
6+'$#% 6+%> F#6$+D'(+AM$ ;A53$'(?Hane?!6+'$#% 6+%> F#6$+D'(+AM$ ;A53$'(?%homas?!6+'$#% 6+%> F#6$+D'(+AM$ ;A53$'(?4eBa?!
"n the above SQL code, the "D column is an autoincrement column. "# we omit the "D in the
SQL "5S38T statements the Derby automatically generates a uni-ue number. "t starts with
number ) and is incremented by one with each subse-uent "5S38T.
Queries
Queries are used to loo( up data #rom the database tables. The S3L3T statement is the main
statement to per#orm -ueries.
)*
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 20/68
Limiting data output
Limiting data output is essential since many databases have thousands even millions o# rows.
Derby does not support the L"'"T clause (nown #rom other databases. Derby ).
introduced 03T: and 600S3T clauses that do the same thing.
ijP '$5$C% , F#>M 4>>9' F$%C F6#'% #>L' >+58!6D QA3%>#E6D Q%6%5$------------------------------------------------- Q QCall oK the Lild Q QMartin $den< Q Q>ld Goriot Q QCousin 4ette
"n the #irst eample, we have #etched only the #irst / rows #rom the B662S table.
ijP '$5$C% , F#>M 4>>9' >FF'$% #>L'!
6D QA3%>#E6D Q%6%5$----------------------------------------------- Q< QHew 'uess@ Q Q+ana0 Q Q%he 4elly oK 7aris Q Q6n Cold blood Q Q4reaBKast at %iKKany
7ith the 600S3T cluase, we s(ip the #irst #our rows and display the rest.
ijP '$5$C% , F#>M 4>>9' >FF'$% #>L' F$%C +$R% < #>L' >+58!6D QA3%>#E6D Q%6%5$----------------------------------------------------------------- Q< QHew 'uess@ Q Q+ana0 Q Q%he 4elly oK 7aris
< rows selected
7e can select a portion o# the rows using the combination o# 600S3T and 03T: clauses.
Derby functions
Derby supports a #ew use#ul #unctions. These built%in #unctions are epressions in which an
SQL (eyword or special operator eecutes some operation.
ijP '$5$C% C>3+%(6D F#>M A3%>#'!-----------
The 6;5T=> is an aggregate #unction that counts the number o# rows accessed in an
epression. There are C authors in the A;T:68S table.
ijP '$5$C% M6+(7#6C$ A' "7#6C$": MAR(7#6C$ A' "MAR":P A;G(7#6C$ A' "A;G": '3M(7#6C$ A' "'3M" F#>M CA#'!
7#6C$ QMAR QA;G Q'3M-----------------------------------------------
$
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 21/68
Q< Q00 Q0@
row selected
"n the above -uery we use other #our #unctions. 'AH=>, '"5=>, A4F=> and S;'=>. The AS
clause gives a label #or a column.
ijP ;A53$' C3##$+%EDA%$!------------
ijP ;A53$' C3##$+% 'C$MA!--------------------------3'$#
4AL;3S ;8835T<DAT3 returns the current date and 4AL;3S ;8835T S:3'A
returns the current schema o# the connection.
Selecting specific ro%s %ith the '(!R! clause
The 7:383 clause can be used to #ilter the results. "t provides a selection criteria to select
only speci#ic rows #rom the data.
ijP '$5$C% , F#>M CA#' L$#$ 7#6C$ P !6D Q+AM$ Q7#6C$------------------------------------------------------ QAudi Q@
QMercedes Q00 Q4entley Q<0 Qummer Q
rows selected
7ith the 7:383 clause we only select the cars which have a price higher than /.
ijP '$5$C% +AM$ F#>M CA#' L$#$ +AM$ 569$ ?Uen?!+AM$------------------------------Citroen;olBswagen
rows selected
7ith a L"23 clause we select speci#ic car names that #it the search pattern. "n our case it is
cars that end in EenE characters.
ijP '$5$C% , F#>M CA#' L$#$ 6D 6+ (: : 0!6D Q+AM$ Q7#6C$------------------------------------------------------ QMercedes Q00 Q4entley Q<0 Qummer Q
< rows selected
$)
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 22/68
The "5 clause can be used to select rows #rom a speci#ic range o# values. The above SQL
statement returns rows that have "Ds e-ual to $, C and .
ijP '$5$C% , F#>M CA#' L$#$ 7#6C$ 4$%L$$+ A+D !6D Q+AM$ Q7#6C$------------------------------------------------------ Q;olvo Q@ QCitroen Q0 Qummer Q Q;olBswagen Q@
rows selected
7e select cars that cost in the range $ and C. 0or this we use the B3T7335 A5D
(eywords #ollowing the 7:383 clause.
Ordering data
6rdering data can be done with the 68D38 B@ clause.
ijP '$5$C% , F#>M CA#' >#D$# 48 7#6C$!6D Q+AM$ Q7#6C$------------------------------------------------------< Q'Boda Q@ QCitroen Q Q;olBswagen Q@ Q;olvo Q0 Qummer Q QAudi Q@ QMercedes Q00
Q4entley Q<
rows selected
7e order the cars by price. The de#ault order type is ascending order.
ijP '$5$C% , F#>M CA#' >#D$# 48 7#6C$ D$'C!6D Q+AM$ Q7#6C$------------------------------------------------------ Q4entley Q< QMercedes Q00 QAudi Q@
0 Qummer Q Q;olvo Q Q;olBswagen Q@@ QCitroen Q< Q'Boda Q
To order data in descending order, we add the D3S (eyword.
Updating and deleting data
5ow we will concern ourselves with updating and deleting data in the A8S table.
ijP 37DA%$ CA#' '$% 7#6C$= L$#$ 6D=! row inserted/updated/deleted
$$
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 23/68
The ;!DAT3 statement is used to modi#y data in a database table. The !8"3 o# a 'ercedes
car is set to CI.
ijP '$5$C% , F#>M CA#' L$#$ 6D=!6D Q+AM$ Q7#6C$------------------------------------------------------ QMercedes Q
row selected
The subse-uent S3L3T statement con#irms the modi#ication o# the data.
ijP C#$A%$ %A45$ CA#'(6D 6+% 7#6MA#8 9$8: +AM$ ;A#CA#(<: 7#6C$ 6+%!
0or the net case, we create a new A8S$ table.
ijP 6+'$#% 6+%> CA#' '$5$C% , F#>M CA#'!
rows inserted/updated/deleted
7e insert all the rows #rom the A8S table into the A8S$ table, thus copying all data.
ijP '$5$C% , F#>M CA#'!6D Q+AM$ Q7#6C$------------------------------------------------------ QAudi Q@ QMercedes Q< Q'Boda Q Q;olvo Q Q4entley Q<@ QCitroen Q0 Qummer Q Q;olBswagen Q@
rows selected
7e chec( the A8S$ table and see that all data was copying 62.
ijP D$5$%$ F#>M CA#' L$#$ 6D=! row inserted/updated/deleted
7e used the D3L3T3 086' statement to delete a rown in the table.
ijP D$5$%$ F#>M CA#'!0 rows inserted/updated/deleted
The D3L3T3 086' statement without the 7:383 clause deletes all rows in the table.
ijP D#>7 %A45$ CA#'! rows inserted/updated/deleted
The D86! TABL3 statement deletes the table completly #rom the database.
R!$)! statements
The 835A'3 statement belongs to the data de#inition language o# the SQL.
$&
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 24/68
ijP #$+AM$ %A45$ F#6$+D' %> M8F#6$+D'!
The 835A'3 TABL3 statement allows us to rename an eisting table. 7e rename a
08"35DS table to '@08"35DS.
ijP #$+AM$ C>53M+ M8F#6$+D'.6D %> F6D!
The 835A'3 6L;'5 statement renames a particular table column
"n the chapter, we have wor(ed with the basics o# the SQL language in Derby.
rogramming 'ith (D)C
"n this chapter, we will create Java programs which will wor( with the Derby database.
The eamples are eecuted in the Derby embedded mode. 7e use the derby.1ar library toconnect to the Derby engine in the embedded mode.
JD"
JDB is an A!" #or the Java programming language that de#ines how a client may access a
database. "t provides methods #or -uerying and updating data in a database. JDB is oriented
towards relational databases. 0rom a technical point o# view, the A!" is as a set o# classes in
the 1ava.s-l pac(age. To use JDB with a particular database, we need a JDB driver #or that
database.
"reating the "RS table
"n the #irst eample, we will create a A8S table and insert I rows into it. Drop the A8S
table #rom the database i# it is already created be#ore running the eample.
pacBage Ietcode!
import java.s2l.Connection!import java.s2l.DriverManager!import java.s2l.'S5$ception!import java.s2l.'tatement!
import java.util.logging.5evel!import java.util.logging.5ogger!
public class CreateCars V
public static void main('tring)* args V
Connection con = null! 'tatement st = null!
'tring url = "jdbcderbytestdb!user=3'$#"!
try V
'ystem.set7roperty("derby.system.home":"/home/janbodnar/programming/derby/dbs"!
$/
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 25/68
con = DriverManager.getConnection(url!
st = con.create'tatement(! st.eecute3pdate("C#$A%$ %A45$ CA#'(6D 6+% 7#6MA#8 9$8:" W "+AM$ ;A#CA#(<: 7#6C$ 6+%"! st.eecute3pdate("6+'$#% 6+%> CA#' ;A53$'(: ?Audi?: @"!
st.eecute3pdate("6+'$#% 6+%> CA#' ;A53$'(: ?Mercedes?:00"! st.eecute3pdate("6+'$#% 6+%> CA#' ;A53$'(<: ?'Boda?: "! st.eecute3pdate("6+'$#% 6+%> CA#' ;A53$'(: ?;olvo?: "! st.eecute3pdate("6+'$#% 6+%> CA#' ;A53$'(: ?4entley?:<"! st.eecute3pdate("6+'$#% 6+%> CA#' ;A53$'(@: ?Citroen?:"! st.eecute3pdate("6+'$#% 6+%> CA#' ;A53$'(0: ?ummer?:"! st.eecute3pdate("6+'$#% 6+%> CA#' ;A53$'(: ?;olBswagen?:@"! DriverManager.getConnection("jdbcderby!shutdown=true"!
X catch ('S5$ception e V
5ogger lgr = 5ogger.get5ogger(CreateCars.class.get+ame(!
iK (((e.get$rrorCode( == TT ("RH".e2uals(e.get'S5'tate( V
lgr.log(5evel.6+F>: "Derby shut down normally": e!
X else V
lgr.log(5evel.'$;$#$: e.getMessage(: e!
X X Kinally V
try V
iK (st Y= null V st.close(! X iK (con Y= null V con.close(! X
X catch ('S5$ception e V 5ogger lgr = 5ogger.get5ogger(CreateCars.class.get+ame(! lgr.log(5evel.LA#+6+G: e.getMessage(: e! X X XX
The eample connects to the Derby in embedded mode. reates a A8S table and adds I
rows into it. 0inally, it shuts down Derby.
'tring url = "jdbcderbytestdb!user=3'$#"!
$C
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 26/68
This is the ;8L to connect to the testdb database. "n the embedded mode and ;S38)$
schema.
'ystem.set7roperty("derby.system.home":"/home/janbodnar/programming/derby/dbs"!
7e set the system property #or the Derby system directory.
con = DriverManager.getConnection(url!
A connection to the Derby database is created. 7hen the connection is created, the Derby
database is booted.
st.eecute3pdate("C#$A%$ %A45$ CA#'(6D 6+% 7#6MA#8 9$8:" W "+AM$ ;A#CA#(<: 7#6C$ 6+%"!st.eecute3pdate("6+'$#% 6+%> CA#' ;A53$'(: ?Audi?: @"!...
7e eecute the SQL statements which create the database and #ill it with some data. 0or
"5S38T, ;!DAT3 and D3L3T3 statements and DDL statements li(e 83AT3 TABL3 we
use the eecute;pdate=> method.
DriverManager.getConnection("jdbcderby!shutdown=true"!
The Derby database engine is shut down.
X catch ('S5$ception e V
5ogger lgr = 5ogger.get5ogger(CreateCars.class.get+ame(!
7e catch the SQL3ception. 7e use the Logger class to log the error message.
iK (((e.get$rrorCode( == TT ("RH".e2uals(e.get'S5'tate( V
lgr.log(5evel.6+F>: "Derby shut down normally": e!
X
7hen the Derby engine is shut down, an SQL3ception is thrown. 7e catch this eception
and log an in#ormation message.
X Kinally V
try V
iK (st Y= null V st.close(! X iK (con Y= null V con.close(! X
"n the #inally clause, we release the resources.
$+
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 27/68
1 javac Ietcode/CreateCars.java1 java -cp .lib/derby.jar Ietcode.CreateCarsFeb 0: < 7M Ietcode.CreateCars main6+F> Derby shut down normallyjava.s2l.'S5$ception Derby system shutdown....
7e compile and run the eample. The shut down o# Derby will end in an SQL3ception.
This is a #eature o# the Derby database.
Retrieving data
5et we will show, how to retrieve data #rom a database table. 7e get all data #rom the
A8S table.
pacBage Ietcode!
import java.s2l.,!import java.util.logging.5evel!import java.util.logging.5ogger!
public class 'electAllCars V
public static void main('tring)* args V
Connection con = null! 'tatement st = null! #esult'et rs = null!
'tring url = "jdbcderbytestdb"!
try V
'ystem.set7roperty("derby.system.home":"/home/janbodnar/programming/derby/dbs"!
con = DriverManager.getConnection(url!
st = con.create'tatement(! rs = st.eecuteSuery("'$5$C% , F#>M 3'$#.CA#'"!
while (rs.net( V 'ystem.out.print(rs.get6nt(! 'ystem.out.print(" "!
'ystem.out.print(rs.get'tring(! 'ystem.out.print(" "! 'ystem.out.println(rs.get'tring(<! X
DriverManager.getConnection("jdbcderby!shutdown=true"!
X catch ('S5$ception e V
5ogger lgr = 5ogger.get5ogger('electAllCars.class.get+ame(!
iK (((e.get$rrorCode( == TT ("RH".e2uals(e.get'S5'tate( V
lgr.log(5evel.6+F>: "Derby shut down normally": e!
$
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 28/68
X else V
lgr.log(5evel.'$;$#$: e.getMessage(: e! X
X Kinally V
try V iK (rs Y= null V rs.close(! X iK (st Y= null V st.close(! X iK (con Y= null V con.close(! X
X catch ('S5$ception e V
5ogger lgr =5ogger.get5ogger('electAllCars.class.get+ame(! lgr.log(5evel.LA#+6+G: e.getMessage(: e! X X XX
7e get all the cars #rom the A8S table and print them to the console.
st = con.create'tatement(!rs = st.eecuteSuery("'$5$C% , F#>M 3'$#.CA#'"!
7e eecute a -uery that selects all columns #rom the A8S table. 7e use the eecuteQuery=>
method. The method eecutes the given SQL statement, which returns a single 8esultSet
ob1ect. The 8esultSet is the data table returned by the SQL -uery. Also note that since we
have not speci#ied the user name in the ;8L, we have to eplicitly mention the schema name
in the SQL statement.
while (rs.net( V 'ystem.out.print(rs.get6nt(! 'ystem.out.print(" "! 'ystem.out.print(rs.get'tring(! 'ystem.out.print(" "!
'ystem.out.println(rs.get'tring(<!X
The net=> method advances the cursor to the net record o# the result set. "t returns #alse,
when there are no more rows in the result set. The get"nt=> and getString=> methods retrieve
the value o# the designated column in the current row o# this 8esultSet ob1ect an intString in
the Java programming language.
1 javac Ietcode/'electAllCars.java1 java -cp .lib/derby.jar Ietcode.'electAllCars Audi @ Mercedes 00
< 'Boda ;olvo
$I
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 29/68
4entley <@ Citroen 0 ummer ;olBswagen @Feb : <<< AM Ietcode.'electAllCars main6+F> Derby shut down normally
java.s2l.'S5$ception Derby system shutdown....
7e compile and run the eample. 7e have a list o# all cars #rom the A8S table o# the testdb
database.
*roperties
"t is a common practice to put the con#iguration data outside the program in a separate #ile.
This way the programmers are more #leible. 7e can change the user, a password or a
connection url without needing to recompile the program. "t is especially use#ul in a dynamic
environment, where is a need #or a lot o# testing, debugging, securing data etc.
"n Java, the !roperties is a class used o#ten #or this. The class is used #or easy reading and
saving o# (eyvalue properties.
db.url=jdbcderbytestdb!user=3'$#db.user=3'$#db.passwd=<Bl2,db.syshome=/home/janbodnar/programming/derby/dbs
7e have a database.properties #ile, in which we have #our (eyvalue pairs. These are
dynamically loaded during the eecution o# the program.
pacBage Ietcode!
import java.io.File6nput'tream!import java.io.File+otFound$ception!import java.io.6>$ception!import java.s2l.,!import java.util.7roperties!import java.util.logging.5evel!import java.util.logging.5ogger!
public class 7roperties$ample V
public static void main('tring)* args V
Connection con = null! 7repared'tatement pst = null! #esult'et rs = null!
7roperties props = new 7roperties(! File6nput'tream in = null!
try V
in = new File6nput'tream("database.properties"! props.load(in!
$*
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 30/68
X catch (File+otFound$ception e V
5ogger lgr =5ogger.get5ogger(7roperties$ample.class.get+ame(! lgr.log(5evel.'$;$#$: e.getMessage(: e!
X catch (6>$ception e V
5ogger lgr =5ogger.get5ogger(7roperties$ample.class.get+ame(! lgr.log(5evel.'$;$#$: e.getMessage(: e!
X Kinally V
try V iK (in Y= null V in.close(! X X catch (6>$ception e V
5ogger lgr =5ogger.get5ogger(7roperties$ample.class.get+ame(! lgr.log(5evel.'$;$#$: e.getMessage(: e! X X
'tring url = props.get7roperty("db.url"! 'tring user = props.get7roperty("db.user"! 'tring passwd = props.get7roperty("db.passwd"!
try V
'ystem.set7roperty("derby.system.home":
props.get7roperty("db.syshome"! con = DriverManager.getConnection(url: user: passwd! pst = con.prepare'tatement("'$5$C% , F#>M CA#'"! rs = pst.eecuteSuery(!
while (rs.net( V 'ystem.out.print(rs.get6nt(! 'ystem.out.print(" "! 'ystem.out.println(rs.get'tring(! X
DriverManager.getConnection("jdbcderby!shutdown=true"!
X catch ('S5$ception e V
5ogger lgr =5ogger.get5ogger(7roperties$ample.class.get+ame(!
iK (((e.get$rrorCode( == TT ("RH".e2uals(e.get'S5'tate( V
lgr.log(5evel.6+F>: "Derby shut down normally": e!
X else V
lgr.log(5evel.'$;$#$: e.getMessage(: e! X
&
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 31/68
X Kinally V
try V iK (rs Y= null V rs.close(! X
iK (pst Y= null V pst.close(! X iK (con Y= null V con.close(! X
X catch ('S5$ception e V
5ogger lgr =5ogger.get5ogger(7roperties$ample.class.get+ame(! lgr.log(5evel.LA#+6+G: e.getMessage(: e! X
X XX
7e connect to the testdb and select all authors #rom the A;T:68S table. The con#iguration
data #or the eample is read #rom the database.properties #ile.
7roperties props = new 7roperties(!File6nput'tream in = null!
try V
in = new File6nput'tream("database.properties"! props.load(in!
The !roperties class is created. The data is loaded #rom the #ile called database.properties,
where we have our con#iguration data.
'tring url = props.get7roperty("db.url"!'tring user = props.get7roperty("db.user"!'tring passwd = props.get7roperty("db.passwd"!
The values are retrieved with the get!roperty=> method.
con = DriverManager.getConnection(url: user: passwd!
5ote that in the de#ault Derby con#iguration, the password is ignored.
*repared statements
5ow we will concern ourselves with prepared statements. 7hen we write prepared
statements, we use placeholders instead o# directly writing the values into the statements.
!repared statements increase security and per#ormance.
"n Java a !reparedStatement is an ob1ect which represents a precompiled SQL statement.
pacBage Ietcode!
&)
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 32/68
import java.s2l.,!import java.util.logging.5evel!import java.util.logging.5ogger!
public class 7repared V public static void main('tring)* args V
Connection con = null! 7repared'tatement pst = null! #esult'et rs = null!
'tring url = "jdbcderbytestdb!user=3'$#"!
int price = ! int id = !
try V 'ystem.set7roperty("derby.system.home":
"/home/janbodnar/programming/derby/dbs"!
con = DriverManager.getConnection(url!
pst = con.prepare'tatement("37DA%$ CA#' '$% 7#6C$ = Z L$#$ 6D= Z"! pst.set6nt(: price! pst.set6nt(: id! pst.eecute3pdate(!
DriverManager.getConnection("jdbcderby!shutdown=true"! X catch ('S5$ception e V
5ogger lgr = 5ogger.get5ogger(7repared.class.get+ame(!
iK (((e.get$rrorCode( == TT ("RH".e2uals(e.get'S5'tate( V
lgr.log(5evel.6+F>: "Derby shut down normally": e!
X else V
lgr.log(5evel.'$;$#$: e.getMessage(: e! X
X Kinally V
try V iK (rs Y= null V rs.close(! X iK (pst Y= null V pst.close(! X iK (con Y= null V con.close(! X
&$
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 33/68
X catch ('S5$ception e V 5ogger lgr = 5ogger.get5ogger(7repared.class.get+ame(! lgr.log(5evel.LA#+6+G: e.getMessage(: e! X X X
X
7e change the price #or a car with id e-ual to $.
int price = !int id = !
These are the values that are going to be set to the prepared statement. These values could
come #rom a user and everything coming #rom users should be considered potentionally
dangerous.
pst = con.prepare'tatement("37DA%$ CA#' '$% 7#6C$ = Z L$#$ 6D = Z"!
:ere we create a prepared statement. 7hen we write prepared statements, we use
placeholders instead o# directly writing the values into the statements. !repared statements
are #aster and guard against SQL in1ection attac(s. The K is a placeholder, which is going to
be #illed later.
pst.set6nt(: price!pst.set6nt(: id!
4alues are bound to the placeholders.
pst.eecute3pdate(!
The prepared statement is eecuted. 7e use the eecute;pdate=> method o# the statement
ob1ect when we donEt epect any data to be returned. This is when we create databases or
eecute "5S38T, ;!DAT3, D3L3T3 statements.
1 javac Ietcode/7repared.java1 java -cp .lib/derby.jar Ietcode.7reparedFeb : 0 AM Ietcode.7repared main'$;$#$ Database ?testdb? shutdown.java.s2l.'S5+on%ransientConnection$ception Database ?testdb? shutdown....
ijP '$5$C% , F#>M CA#' L$#$ 6D=!6D Q+AM$ Q7#6C$------------------------------------------------------ QMercedes Q
row selected
7e compile the eample. 8un it. And chec( the outcome with the i1 tool.
&&
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 34/68
"olumn headers
5et we will show, how to print column headers with the data #rom the database table. 7e
re#er to column names as 'etaData. 'etaData is data about the core data in the database.
pacBage Ietcode!
import java.s2l.,!import java.util.Formatter!import java.util.logging.5evel!import java.util.logging.5ogger!
public class Columneaders V
public static void main('tring)* args V
Connection con = null!
7repared'tatement pst = null! #esult'et rs = null!
'tring url = "jdbcderbytestdb!user=3'$#"!
try V
'ystem.set7roperty("derby.system.home":"/home/janbodnar/programming/derby/dbs"!
con = DriverManager.getConnection(url! 'tring 2uery = "'$5$C% +AM$: %6%5$ From A3%>#': " W "4ooBs L$#$ A3%>#'.6D=4>>9'.A3%>#E6D"!
pst = con.prepare'tatement(2uery!
rs = pst.eecuteSuery(!
#esult'etMetaData meta = rs.getMetaData(!
'tring colname = meta.getColumn+ame(! 'tring colname = meta.getColumn+ame(!
Formatter Kmt = new Formatter(! Kmt.Kormat("U-sUs": colname: colname! 'ystem.out.println(Kmt!
while (rs.net( V Formatter Kmt = new Formatter(! Kmt.Kormat("U-s": rs.get'tring(! 'ystem.out.print(Kmt! 'ystem.out.println(rs.get'tring(! X
DriverManager.getConnection("jdbcderby!shutdown=true"!
X catch ('S5$ception e V
5ogger lgr = 5ogger.get5ogger(Columneaders.class.get+ame(!
iK (((e.get$rrorCode( == TT ("RH".e2uals(e.get'S5'tate( V
&/
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 35/68
lgr.log(5evel.6+F>: "Derby shut down normally": e!
X else V
lgr.log(5evel.'$;$#$: e.getMessage(: e! X
X Kinally V
try V iK (rs Y= null V rs.close(! X iK (pst Y= null V pst.close(! X iK (con Y= null V con.close(! X
X catch ('S5$ception e V 5ogger lgr =5ogger.get5ogger(Columneaders.class.get+ame(! lgr.log(5evel.LA#+6+G: e.getMessage(: e! X X XX
"n this program, we select authors #rom the A;T:68S table and their boo(s #rom the
B662S table. 7e print the names o# the columns returned in the result set. 7e #ormat the
output. The SQL #ile to create the tables is located in the #irst chapter o# this tutorial.
'tring 2uery = "'$5$C% +AM$: %6%5$ From A3%>#': " W "4ooBs L$#$ A3%>#'.6D=4>>9'.A3%>#E6D"!
This is the SQL statement which 1oins authors with their boo(s.
#esult'etMetaData meta = rs.getMetaData(!
To get the column names we need to get the 8esultSet'etaData. "t is an ob1ect that can be
used to get in#ormation about the types and properties o# the columns in a 8esultSet ob1ect.
'tring colname = meta.getColumn+ame(!'tring colname = meta.getColumn+ame(!
0rom the obtained metadata, we get the column names.
Formatter Kmt = new Formatter(!Kmt.Kormat("U-sUs": colname: colname!'ystem.out.println(Kmt!
7e print the column names to the console. The 0ormatter ob1ect #ormats the data.
while (rs.net( V Formatter Kmt = new Formatter(! Kmt.Kormat("U-s": rs.get'tring(!
&C
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 36/68
'ystem.out.print(Kmt! 'ystem.out.println(rs.get'tring(!X
7e print the data to the console. 7e again use the 0ormatter ob1ect to #ormat the data. The
#irst column is $) characters wide and is aligned to the le#t.
1 javac Ietcode/Columneaders.java1 java -cp .lib/derby.jar Ietcode.Columneaders+AM$ %6%5$HacB 5ondon Call oK the LildHacB 5ondon Martin $denonore de 4alIac >ld Goriotonore de 4alIac Cousin 4ette5ion Feuchtwanger Hew 'uess$mile Jola +ana$mile Jola %he 4elly oK 7aris%ruman Capote 6n Cold blood
%ruman Capote 4reaBKast at %iKKanyFeb : 7M Ietcode.Columneaders main6+F> Derby shut down normallyjava.s2l.'S5$ception Derby system shutdown....
The eample is compiled and eecuted.
'riting images
Some people pre#er to put their images into the database, some pre#er to (eep them on the #ile
system #or their applications. Technical di##iculties arise when we wor( with millions o#
images. "mages are binary data. Derby has a special data type to store binary data called
BL6B =Binary Large 6b1ect>.
7e create a new table called "'AF3S #or this and the #ollowing eample.
ijP C#$A%$ %A45$ 6MAG$'(6D 6+% 7#6MA#8 9$8: DA%A 45>4! rows inserted/updated/deleted
The DATA column has the BL6B type. There we will insert the encoded binary data.
pacBage Ietcode!
import java.io.File!import java.io.File6nput'tream!import java.io.File+otFound$ception!import java.s2l.,!import java.util.logging.5evel!import java.util.logging.5ogger!
public class Lrite6mage V
public static void main('tring)* args V
Connection con = null!
7repared'tatement pst = null!
File6nput'tream Kin = null!
&+
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 37/68
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 38/68
"n this eample, we read a 1pg image #rom the current wor(ing directory and insert in into the
"'AF3S table.
File img = new File("woman.jpg"!Kin = new File6nput'tream(img!
7e create a 0ile ob1ect #or the image #ile. To read bytes #rom this #ile, we create a
0ile"nputStream ob1ect.
pst = con.prepare'tatement("6+'$#% 6+%> 6MAG$'(6D: DA%A ;A53$'(: Z"!
This SQL statement inserts the image into the
pst.set4inary'tream(: Kin: (int img.length(!
The binary stream is set to the prepared statement. The parameters o# the setBinaryStream=>
method are the parameter inde to bind, the input stream and the number o# bytes in thestream.
pst.eecute3pdate(!
7e eecute the statement.
Reading images
"n the previous eample, we have inserted an image into the database table. 5ow we are
going to read the image bac( #rom the table.
pacBage Ietcode!
import java.io.File>utput'tream!import java.io.6>$ception!import java.s2l.,!import java.util.logging.5evel!import java.util.logging.5ogger!
public class #ead6mage V
public static void main('tring)* args V
Connection con = null! 7repared'tatement pst = null! #esult'et rs = null!
File>utput'tream Kos = null!
'tring url = "jdbcderbytestdb!user=3'$#"!
try V
'ystem.set7roperty("derby.system.home": "/home/janbodnar/programming/derby/dbs"!
'ystem.out.println('ystem.get7roperty("user.dir"!
&I
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 39/68
con = DriverManager.getConnection(url!
'tring 2uery = "'$5$C% DA%A F#>M 6MAG$' L$#$ 6D = "! pst = con.prepare'tatement(2uery!
#esult'et result = pst.eecuteSuery(!
result.net(!
Kos = new File>utput'tream("woman.jpg"!
4lob blob = result.get4lob("DA%A"! int len = (int blob.length(!
byte)* buK = blob.get4ytes(: len!
Kos.write(buK: : len!
DriverManager.getConnection("jdbcderby!shutdown=true"!
X catch (6>$ception e V 5ogger lgr = 5ogger.get5ogger(#ead6mage.class.get+ame(! lgr.log(5evel.'$;$#$: e.getMessage(: e!
X catch ('S5$ception e V
5ogger lgr = 5ogger.get5ogger(#ead6mage.class.get+ame(!
iK (((e.get$rrorCode( == TT ("RH".e2uals(e.get'S5'tate( V
lgr.log(5evel.6+F>: "Derby shut down normally": e!
X else V
lgr.log(5evel.'$;$#$: e.getMessage(: e! X
X Kinally V
try V iK (rs Y= null V rs.close(! X iK (pst Y= null V pst.close(! X iK (con Y= null V con.close(! X
X catch ('S5$ception e V 5ogger lgr = 5ogger.get5ogger(#ead6mage.class.get+ame(! lgr.log(5evel.LA#+6+G: e.getMessage(: e! X X XX
7e read one image #rom the "'AF3S table.
&*
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 40/68
'tring 2uery = "'$5$C% DA%A F#>M 6MAG$' L$#$ 6D = "!
6ne record is selected.
Kos = new File>utput'tream("woman.jpg"!
The 0ile6utputStream ob1ect is created to write to a #ile. "t is meant #or writing streams o#
raw bytes such as image data.
4lob blob = result.get4lob("DA%A"!
7e get the image data #rom the DATA column by calling the getBlob=> method.
int len = (int blob.length(!
7e #ind out the length o# the blob data. "n other words, we get the number o# bytes.
byte)* buK = blob.get4ytes(: len!
The getBytes=> method retrieves all bytes o# the BL6B ob1ect, as an array o# bytes.
Kos.write(buK: : len!
The bytes are written to the output stream. The image is created on the #ilesystem.
Transaction support
A transaction is an atomic unit o# database operations against the data in one or moredatabases. The e##ects o# all the SQL statements in a transaction can be either all committed
to the database or all rolled bac(.
7hen a connection is created, it is in autocommit mode. This means that each individual
SQL statement is treated as a transaction and is automatically committed right a#ter it is
eecuted. This is true #or all JDB drivers, including the DerbyEs one. To start a new
transaction, we turn the autocommit o##.
"n direct SQL, a transaction is started with B3F"5 T8A5SAT"65 statement and ended
with 35D T8A5SAT"656''"T statement. "n Derby these statements are B3F"5 and
6''"T. :owever, when wor(ing with drivers these statements are omitted. They arehandled by the driver. 3act details are speci#ic to the driver. 0or eample psycopg$ !ython
driver starts a transaction a#ter the #irst SQL statement. "# we want the autocommit mode, we
must be set the autocommit property to True. "n constrast, JDB driver is by de#ault in the
autocommit mode. And to start a new transaction, the autocommit must be turned o##.
pacBage Ietcode!
import java.s2l.Connection!import java.s2l.DriverManager!import java.s2l.'S5$ception!import java.s2l.'tatement!
import java.util.logging.5evel!import java.util.logging.5ogger!
/
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 41/68
public class %ransaction V
public static void main('tring)* args V
Connection con = null!
'tatement st = null!
'tring url = "jdbcderbytestdb!user=3'$#"!
try V
'ystem.set7roperty("derby.system.home": "/home/janbodnar/programming/derby/dbs"!
con = DriverManager.getConnection(url!
st = con.create'tatement(!
con.setAutoCommit(Kalse!
st.eecute3pdate("37DA%$ A3%>#' '$% +AM$ = ?5eo %olstoy? " W "L$#$ 6d = "! st.eecute3pdate("37DA%$ 4>>9' '$% %6%5$ = ?Lar and 7eace? " W "L$#$ 6d = "! st.eecute3pdate("37DA%$ 4>>9' '$% %6%5 = ?Anna 9arenina? " W "L$#$ 6d = "!
con.commit(!
DriverManager.getConnection("jdbcderby!shutdown=true"!
X catch ('S5$ception e V
5ogger lgr = 5ogger.get5ogger(%ransaction.class.get+ame(!
iK (((e.get$rrorCode( == TT ("RH".e2uals(e.get'S5'tate( V
lgr.log(5evel.6+F>: "Derby shut down normally": e!
X else V
iK (con Y= null V try V con.rollbacB(! X catch ('S5$ception e V lgr.log(5evel.LA#+6+G: e.getMessage(: e! X X
lgr.log(5evel.'$;$#$: e.getMessage(: e! X
X Kinally V
try V iK (st Y= null V st.close(!
/)
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 42/68
X iK (con Y= null V con.close(! X
X catch ('S5$ception e V
5ogger lgr = 5ogger.get5ogger(%ransaction.class.get+ame(! lgr.log(5evel.LA#+6+G: e.getMessage(: e! X X XX
"n this program, we want to change the name o# the author in the #irst row o# the A;T:68S
table. 7e must also change the boo(s associated with this author. "# we change the author and
do not change the authorEs boo(s, the data is corrupted.
con.setAutoCommit(Kalse!
To wor( with transactions, we must set the autocommit to #alse. By de#ault, a database
connection is in autocommit mode. "n this mode each statement is committed to the database,
as soon as it is eecuted. A statement cannot be undone. 7hen the autocommit is turned o##,
we commit the changes by calling the commit=> or roll it bac( by calling the rollbac(=>
method.
st.eecute3pdate("37DA%$ 4>>9' '$% %6%5 = ?Anna 9arenina? " W "L$#$ 6d = "!
The third SQL statement has an error. There is no T"TL column in the B662S table.
con.commit(!
"# there is no eception, the transaction is committed. "# the autocommit is turned o##, we
must eplicitly call the commit=> method.
iK (con Y= null V
try V con.rollbacB(! X catch ('S5$ception e V lgr.log(5evel.LA#+6+G: e.getMessage(: e!
XX
"n case o# an eception other than the Derby system shutdown, the transaction is rolled bac(.
5o changes are committed to the database.
1 javac Ietcode/%ransaction.java1 java -cp .lib/derby.jar Ietcode.%ransactionFeb : < 7M Ietcode.%ransaction main'$;$#$ ?%6%5? is not a column in table or ;%6 ?3'$#.4>>9'?.java.s2l.'S5'ynta$rror$ception ?%6%5? is not a column in table or ;%6?3'$#.4>>9'?.
...ijP '$5$C% +AM$: %6%5$ F#>M A3%>#': 4>>9' L$#$
/$
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 43/68
P A3%>#'.6D = 4>>9'.A3%>#E6D!+AM$ Q%6%5$------------------------------------------------------------HacB 5ondon QCall oK the LildHacB 5ondon QMartin $denonore de 4alIac Q>ld Goriot
onore de 4alIac QCousin 4ette5ion Feuchtwanger QHew 'uess$mile Jola Q+ana$mile Jola Q%he 4elly oK 7aris%ruman Capote Q6n Cold blood%ruman Capote Q4reaBKast at %iKKany
rows selected
The eecution #ails with the ET"TLE is not a column in table message. An eception was
thrown. The transaction was rolled bac( and no changes too( place.
:owever, without a transaction, the data is not sa#e.
pacBage Ietcode!
import java.s2l.Connection!import java.s2l.DriverManager!import java.s2l.'S5$ception!import java.s2l.'tatement!import java.util.logging.5evel!import java.util.logging.5ogger!
public class +on%ransaction V
public static void main('tring)* args V
Connection con = null! 'tatement st = null!
'tring url = "jdbcderbytestdb!user=3'$#"!
try V
'ystem.set7roperty("derby.system.home":
"/home/janbodnar/programming/derby/dbs"!
con = DriverManager.getConnection(url!
st = con.create'tatement(!
st.eecute3pdate("37DA%$ A3%>#' '$% +AM$ = ?5eo %olstoy? " W "L$#$ 6d = "! st.eecute3pdate("37DA%$ 4>>9' '$% %6%5$ = ?Lar and 7eace? " W "L$#$ 6d = "! st.eecute3pdate("37DA%$ 4>>9' '$% %6%5 = ?Anna 9arenina? " W "L$#$ 6d = "!
DriverManager.getConnection("jdbcderby!shutdown=true"!
/&
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 44/68
X catch ('S5$ception e V
5ogger lgr = 5ogger.get5ogger(+on%ransaction.class.get+ame(!
iK (((e.get$rrorCode( ==
TT ("RH".e2uals(e.get'S5'tate( V
lgr.log(5evel.6+F>: "Derby shut down normally": e!
X else V
lgr.log(5evel.'$;$#$: e.getMessage(: e! X
X Kinally V
try V iK (st Y= null V
st.close(! X iK (con Y= null V con.close(! X
X catch ('S5$ception e V 5ogger lgr =5ogger.get5ogger(+on%ransaction.class.get+ame(! lgr.log(5evel.LA#+6+G: e.getMessage(: e! X X X
X
7e have the same eample. This time, without the transaction support.
1 javac Ietcode/+on%ransaction.java1 java -cp .lib/derby.jar Ietcode.+on%ransactionFeb : << 7M Ietcode.+on%ransaction main'$;$#$ ?%6%5? is not a column in table or ;%6 ?3'$#.4>>9'?.java.s2l.'S5'ynta$rror$ception ?%6%5? is not a column in table or ;%6?3'$#.4>>9'?....
ijP '$5$C% +AM$: %6%5$ F#>M A3%>#': 4>>9' L$#$
P A3%>#'.6D = 4>>9'.A3%>#E6D!+AM$ Q%6%5$----------------------------------------------------------------5eo %olstoy QLar and 7eace5eo %olstoy QMartin $denonore de 4alIac Q>ld Goriotonore de 4alIac QCousin 4ette5ion Feuchtwanger QHew 'uess$mile Jola Q+ana$mile Jola Q%he 4elly oK 7aris%ruman Capote Q6n Cold blood%ruman Capote Q4reaBKast at %iKKany
rows selected
//
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 45/68
An eception is thrown again. Leo Tolstoy did not write 'artin 3den. The data is corrupted.
atch updates
7hen we need to update data with multiple statements, we can use batch updates. Batch
updates are available #or "5S38T, ;!DAT3, D3L3T3 statements as well as #or 83AT3TABL3 and D86! TABL3 statements.
pacBage Ietcode!
import java.s2l.,!import java.util.logging.5evel!import java.util.logging.5ogger!
public class 4atch3pdates V
public static void main('tring)* args V
Connection con = null! 'tatement st = null! #esult'et rs = null!
'tring url = "jdbcderbytestdb!user=3'$#"!
try V
'ystem.set7roperty("derby.system.home": "/home/janbodnar/programming/derby/dbs"!
con = DriverManager.getConnection(url!
con.setAutoCommit(Kalse! st = con.create'tatement(!
st.add4atch("D$5$%$ F#>M CA#'"! st.add4atch("6+'$#% 6+%> CA#' ;A53$'(: ?Audi?: @"! st.add4atch("6+'$#% 6+%> CA#' ;A53$'(: ?Mercedes?: 00"! st.add4atch("6+'$#% 6+%> CA#' ;A53$'(<: ?'Boda?: "! st.add4atch("6+'$#% 6+%> CA#' ;A53$'(: ?;olvo?: "! st.add4atch("6+'$#% 6+%> CA#' ;A53$'(: ?4entley?: <"! st.add4atch("6+'$#% 6+%> CA#' ;A53$'(@: ?Citroen?: "! st.add4atch("6+'$#% 6+%> CA#' ;A53$'(0: ?ummer?: "! st.add4atch("6+'$#% 6+%> CA#' ;A53$'(: ?;olBswagen?: @"! st.add4atch("6+'$#% 6+%> CA#' ;A53$'(: ?Haguar?: "!
int counts)* = st.eecute4atch(!
con.commit(!
'ystem.out.println("Committed " W counts.length W " updates"!
DriverManager.getConnection("jdbcderby!shutdown=true"!
X catch ('S5$ception e V
5ogger lgr = 5ogger.get5ogger(4atch3pdates.class.get+ame(!
iK (((e.get$rrorCode( == TT ("RH".e2uals(e.get'S5'tate( V
/C
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 46/68
lgr.log(5evel.6+F>: "Derby shut down normally": e!
X else V
iK (con Y= null V
try V con.rollbacB(! X catch ('S5$ception e V lgr.log(5evel.LA#+6+G: e.getMessage(: e! X X
lgr.log(5evel.'$;$#$: e.getMessage(: e! X
X Kinally V
try V
iK (rs Y= null V rs.close(! X iK (st Y= null V st.close(! X iK (con Y= null V con.close(! X
X catch ('S5$ception e V 5ogger lgr =5ogger.get5ogger(4atch3pdates.class.get+ame(!
lgr.log(5evel.LA#+6+G: e.getMessage(: e! X X XX
This is an eample program #or a batch update. 7e delete all rows #rom the A8S table and
insert nine rows into it.
con.setAutoCommit(Kalse!
Autocommit should always be turned o## when doing batch updates.
st.add4atch("D$5$%$ F#>M CA#'"!st.add4atch("6+'$#% 6+%> CA#' ;A53$'(: ?Audi?: @"!st.add4atch("6+'$#% 6+%> CA#' ;A53$'(: ?Mercedes?: 00"!st.add4atch("6+'$#% 6+%> CA#' ;A53$'(<: ?'Boda?: "!...
7e use teh addBatch=> method to add a new command to the statement.
int counts)* = st.eecute4atch(!
A#ter adding all commands, we call the eecuteBatch=> to per#orm a batch update. The
method returns an array o# committed changes.
/+
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 47/68
con.commit(!
Batch updates are committed in a transaction.
1 javac Ietcode/4atch3pdates.java1 java -cp .lib/derby.jar Ietcode.4atch3pdates Committed updatesFeb : < 7M Ietcode.4atch3pdates main6+F> Derby shut down normallyjava.s2l.'S5$ception Derby system shutdown....
ijP '$5$C% , F#>M CA#'!6D Q+AM$ Q7#6C$------------------------------------------------------ QAudi Q@ QMercedes Q00< Q'Boda Q Q;olvo Q Q4entley Q<@ QCitroen Q0 Qummer Q Q;olBswagen Q@ QHaguar Q
7e have success#ully recreated the A8S table.
"n the chapter, we did some JDB programming with Java and Derby.
!ecurity
"n the net chapter, we will mention security options with Derby.
There are two basic security concepts that we will brie#ly mention in this chapter. The user
authentication and user authori9ation. *ser authentication is veri#ying user credentials
be#ore giving access to the Derby system. *ser authori+ation is a means o# giving
permissions to read andor write to a Derby database.
0urthermore, Derby allows to encrypt database #iles stored on the dis(. Derby networ( tra##ic
may be encrypted with SSLTLS cryptographic protocols.
The Derby defaults
By de#ault, Derby does not re-uire user authentication. The user name becomes the de#ault
schema in the program and the user password is ignored. To enable authentication, we must
modi#y the Derby properties. The user authori9ation is turned o##. Also Derby does not have a
database superuser.
The database o%ner
The database owner is the user, that has created the database. "# the database is created
without supplying a user the database owner is set to the de#ault authori9ation identi#ier, A!!.ontrolling the database owner is important when we enable SQL authori9ation.
/
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 48/68
Database encryption
Derby provides a way #or us to encrypt the data on dis(. The user who boots the database
must provide a boot password. A database can be encrypted at the moment o# its creation. "t
is also possible to encrypt an eisting non%encrypted database. 7hen we encrypt a database
we must also speci#y a boot password, which is an alpha%numeric string used to generate theencryption (ey.
ijP C>++$C% ?jdbcderbytestdb!create=true!data$ncryption=true!boot7assword=<<BBll22,,?!
7e can encrypt the database, when we create it. 7e set the data3ncryption property to true
and provide a boot password. 5ow every time the database is booted, we must provide the
boot password.
ijP C>++$C% ?jdbcderbytestdb?!
$##># RH Failed to start database ?testdb? with class loadersun.misc.5auncher1AppClass5oader[<@be: see the net eception Kordetails.$##># R4M@ 'tartup Kailed. An encrypted database cannot be accessedwithoutthe correct boot password.
"n the embedded mode, when we connect to the database, we also boot it. The Derby shows
the above error message, when we try to connect to an ecrypted database without the boot
password.
ijP C>++$C% ?jdbcderbytestdb!boot7assword=<<BBll22,,?!
ijP '>L C>++$C%6>+'!C>++$C%6>+, - jdbcderbytestdb, = current connection
7ith the correct boot password, we have success#ully connected to the testdb database.
uthentication
Authentication is restricting access to the proper users. Authentication is turned o## by de#ault
in Derby.
Derby has three ways to provide authentication.
• 3ternal authentication with LDA!
• ustom Java class
• Built%in system
The o##icial Derby documentation warns that the DerbyEs built%in authentication mechanism
is suitable only #or development and testing purposes. "t is strongly recommended that
production systems rely on LDA! or a user%de#ined class #or authentication.
Embedded
Authentication can be set at two levels. At a system level or at a database level.
/I
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 49/68
ijP CA55 '8'C'E3%65.'8'C'E'$%EDA%A4A'$E7#>7$#%8(?derby.user.user?:?<Bl2,?! rows inserted/updated/deletedijP CA55'8'C'E3%65.'8'C'E'$%EDA%A4A'$E7#>7$#%8(?derby.connection.re2uireAuthentication?:
?true?! rows inserted/updated/deleted
The above two statements enable user authentication #or the currently connected database at a
database level. 7e have created a user with a password and have enabled the
derby.connection.re-uireAuthentication property.
ijP C>++$C% ?jdbcderbytestdb?!$##># Connection authentication Kailure occurred. #eason 6nvalidauthentication..ijP C>++$C% ?jdbcderbytestdb!user=user!password=<Bl2,?!ijP '>L C>++$C%6>+'!
C>++$C%6>+, - jdbcderbytestdb, = current connection
A#ter enabling user authentication, we must provide user credentials, when we want to
connect to the testdb database.
Client/Server
"n the net eamples, we will wor( with the Derby in the lientServer mode. 7e have an
encrypted testdb database.
1 start+etworB'erver T
The Derby server is started.
ijP C>++$C%?jdbcderby//localhost0/dbs/testdb!boot7assword=<<BBll22,,?!
7hen we connect to the testdb database #or the #irst time, we must provide the boot
password. "t is because previously we have encrypted the testdb database.
ijP C>++$C% ?jdbcderby//localhost0/dbs/testdb?!ijP '>L C>++$C%6>+'!C>++$C%6>+, - jdbcderby//localhost0/dbs/testdb, = current connection
7e do not need to boot the database in the lientServer mode once it is already started.
;nli(e in the embedded mode, where each time we connect to the database, we also boot it.
"n the net step, we are going to enable the user authentication in the lientServer mode. 0or
this, we need to edit the derby.properties #ile.
1 stop+etworB'erver
/*
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 50/68
0irst, we stop the Derby server i# it is running. 5ote that a#ter user authentication was enabled
we need to provide user credentials to stop the server. The stop5etwor(Server script ta(es
%user and %password options.
1 cat dbs/derby.properties
derby.connection.re2uireAuthentication=truederby.user.user=<Bl2,derby.authentication.provider=4365%6+
"n the Derby system directory, we modi#y the derby.properties #ile. "# the #ile is not present,
we create it. "n the property #ile we enable the authentication and create a user with a
password. 7e also set the authentication provider to the Derby B;"LT"5.
1 start+etworB'erver T
7e start the Derby server.
1 java -Dderby.system.home=/home/janbodnar/programming/derby/dbs O-Dij.protocol=jdbcderby -jar 1D$#48E>M$/lib/derbyrun.jar ijij version .ijP
7e launch the i1 tool.
ijP C>++$C% ?jdbcderbytestdb!boot7assword=<<BBll22,,?!$##># Connection authentication Kailure occurred. #eason 6nvalidauthentication..
7e try to connect to the testdb database. Since the Derby server was restarted, we provide the
boot password. :owever, we see an error message. This is because we have enabled user
authentication. 7e must also provide user credentials.
ijP C>++$C% ?jdbcderbytestdb!user=user!password=<Bl2,!boot7assword=<<BBll22,,?!
7ith this connection string, we have success#ully connected to the testdb database.
User authori+ation
;ser authori9ation in Derby enables to grant and revo(e permissions to access a system,database, ob1ect or SQL action. 7e can set the user authori9ation properties in Derby as
system%level properties or database%level properties.
Derby has several properties, that a##ect the user authori9ation. The
derby.database.de#aultonnection'ode property controls the de#ault access mode. "# the
property is not set, the property de#aults to #ullAccess, which is read%write access. The other
two options are noAccess and read6nlyAccess. 7ith the derby.database.#ullAccess;sers and
derby.database.read6nlyAccess;sers we control which users can have read%write and which
read%only access to a database. The derby.database.s-lAuthori9ation property enables SQL
standard authori9ation. 7hen the derby.database.s-lAuthori9ation property is set to true,
ob1ect owners can use the F8A5T and 834623 SQL statements to set the user permissions#or speci#ic database ob1ects or #or speci#ic SQL actions.
C
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 51/68
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 52/68
ijP 6+'$#% 6+%> 3'$#.CA#' ;A53$'(: ?%oyota?: 0!$##># An 'S5 data change is not permitted Kor a read-onlyconnection:user or database.
:owever, trying to modi#y data in the A8S table leads to an error. !ermission is not granted
to per#orm changes.
ijP D6'C>++$C%!ijP C>++$C% ?jdbcderby//localhost/testdb!user=user!password=<Bl2,?!
7e close the connection and connect as user)$. This user was given #ull access in the
properties #ile. 3ven i# user)$ is the owner o# the database and owner o# the A8S table, he
cannot modi#y the table unless given #ull access with the Derby properties.
ijP 6+'$#% 6+%> CA#' ;A53$'(: ?%oyota?: 0!
row inserted/updated/deletedijP '$5$C% , F#>M CA#' L$#$ 6D = !6D Q+AM$ Q7#6C$------------------------------------------------------ Q%oyota Q0
row selected
7e have success#ully added a new row into the A8S table.
SQL authorization
The owner o# the database or an ob1ect li(e table can #urther restrict permissions to wor( withdatabase ob1ects. 7e can use F8A5T and 834623 statements to give or withdraw
permissions. The owner o# the database, table is the current user, that has created the
database, table. 5ote that the derby.database.de#aultonnection'ode overrides the
permissions given by the F8A5T statement. So i# a user has read6nlyAccess given by the
de#ault connection mode it cannot modi#y database ob1ects even i# he was given permission
by the F8A5T statement.
7hen the derby.database.s-lAuthori9ation property is set to true, ob1ect owners can use the
F8A5T and 834623 SQL statements to set the user permissions #or speci#ic database
ob1ects or #or speci#ic SQL actions. 5ote that setting system%wide property in the
derby.properties #ile is effective only for ne' databases. 0or eisting databases, we can onlyset database%wide derby.database.s-lAuthori9ation property. A#ter we set the
derby.database.s-lAuthori9ation property to true, we cannot set the property bac( to #alse.
ijP CA55'8'C'E3%65.'8'C'E'$%EDA%A4A'$E7#>7$#%8(?derby.database.s2lAuthoriIation?:?true?!
The derby.database.s-lAuthori9ation property has been set to true. The property is static. 7e
must reboot the testdb database to ma(e the property wor(.
ijP C>++$C% ?jdbcderby//localhost/testdb!shutdown=true!user=user!password=<Bl2,?!
C$
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 53/68
ijP C>++$C% ?jdbcderby//localhost/testdb!user=user!password=<Bl2,!boot7assword=<<BBll22,,?!
7e shut down the testdb database and start it again.
ij(C>++$C%6>+P G#A+% '$5$C% >+ CA#' %> user! rows inserted/updated/deleted
7e provide S3L3T privileges to user)C on table A8S.
ij(C>++$C%6>+P 37DA%$ CA#' '$% 7#6C$=0 L$#$ 6D=! row inserted/updated/deleted
ij(C>++$C%6>+P '$5$C% , F#>M CA#'!6D Q+AM$ Q7#6C$------------------------------------------------------ QAudi Q@ QMercedes Q00
< Q'Boda Q Q;olvo Q Q4entley Q<@ QCitroen Q0 Qummer Q Q;olBswagen Q@ Q%oyota Q0
The user)$ as the owner o# the table has #ull privileges. The above commands con#irm that he
has ;!DAT3 and S3L3T privileges on the A8S table.
ij(C>++$C%6>+P D6'C>++$C%!
ijP C>++$C% ?jdbcderby//localhost/testdb!user=user!password=Bl?!ij(C>++$C%6>+P '$5$C% , F#>M 3'$#.CA#'!$##># 3ser ?3'$#? does not have '$5$C% permissionon column ?6D? oK table ?3'$#?.?CA#'?.
7e disconnect #rom the database and connect as user)/. Trying to eecute S3L3T
statement leads to an error. The user)/ does not have the privileges to S3L3T data #rom the
A8S table.
ij(C>++$C%6>+P D6'C>++$C%!ijP C>++$C% ?jdbcderby//localhost/testdb!user=user!
password=<rrWW?!
ijP '$5$C% , F#>M 3'$#.CA#'!6D Q+AM$ Q7#6C$------------------------------------------------------ QAudi Q@ QMercedes Q00< Q'Boda Q Q;olvo Q Q4entley Q<@ QCitroen Q0 Qummer Q Q;olBswagen Q@
Q%oyota Q0
rows selected
C&
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 54/68
5et we connect as user)C. The user can select data #rom the A8S table.
ij(C>++$C%6>+P '$5$C% , F#>M 3'$#.A3%>#'!$##># 3ser ?3'$#? does not have '$5$C%permission on column ?6D? oK table ?3'$#?.?A3%>#'?.
But he cannot select data #rom the A;T:68S table. !ermissions to select data #rom this
table were not given by the table owner user)$.
ij(C>++$C%6>+P 37DA%$ 3'$#.CA#' '$% 7#6C$=0 L$#$ 6D=!$##># An 'S5 data change is not permitted Kor a read-onlyconnection: user or database.
The user)C also has no ;!DAT3 privileges on the A8S table.
"n the chapter, we dealt with security options in Derby.
,orking 'ith Apache omcat
"n this chapter, we will show how we can put together Derby with Apache Tomcat web
container.
Apache Tomcat is a web container #or the Java programming language. "t is used to serve JS!
pages and servlets. Apache Tomcat can be easily put together to wor( with Derby. Derby has
a derby.'ar #ile in its lib subdirectory. This web archive is simply used to control the Derby
database. Both Tomcat and Derby are pro1ects o# the Apache So#tware #oundation.
1 pwd/home/janbodnar/bin/tomcat1 ls lib/derby,lib/derbyclient.jar lib/derby.jar lib/derbynet.jar
0irst we have to copy the derbyclient.1ar, derby.1ar and derbynet.1ar #iles into the lib
subdirectory o# the Tomcat installation directory.
1 ls webappsderby.war docs eamples host-manager manager #>>%
Then we have to copy the derby.war #ile into the webapps subdirectory #ile o# the Tomcatinstallation directory. 7hen the Tomcat starts, the #ile is unpac(ed and deployed.
1 eport HA;AE>7%'=-Dderby.system.home=/home/janbodnar/programming/derby/dbs
7hen we start Derby via Tomcat, the D38B@<6!TS variable is not ta(en into account. The
derby.system.home must be set prior to starting the Tomcat and Derby servers. 7e can set
the Derby system directory in the JA4A<6!TS variable.
1 bin/startup.sh3sing CA%A56+AE4A'$ /home/janbodnar/bin/tomcat
3sing CA%A56+AE>M$ /home/janbodnar/bin/tomcat3sing CA%A56+AE%M7D6# /home/janbodnar/bin/tomcat/temp
C/
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 55/68
3sing H#$E>M$ /home/janbodnar/bin/[email protected]<3sing C5A''7A% /home/janbodnar/bin/tomcat/bin/bootstrap.jar/home/janbodnar/bin/tomcat/bin/tomcat-juli.jar
7ith the startup.sh script we start the Tomcat server.
0igure Tomcat startup page
7e see the Tomcat welcome page when we navigate to localhostII which is the de#ault
url, on which Tomcat listens.
0igure Derby start
To start the Derby database, we navigate to localhostIIderbyderbynet. This will start the
Derby. 7e have several buttons which can be used to startstop the server, enabledisable
logging or tracing.
\load-on-startupP\/load-on-startupP
7e have to navigate to the above mentioned url each time, we start the Tomcat server. To
automatically start Derby, we can add the above line inside the the MservletN tag o# theweb.ml #ile. The #ile is located in webappsderby73B%"50 directory.
CC
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 56/68
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 57/68
6D Q+AM$ Q7#6C$------------------------------------------------------ QAudi Q@ QMercedes Q00< Q'Boda Q Q;olvo Q
Q4entley Q<@ QCitroen Q0 Qummer Q Q;olBswagen Q@
rows selected
This is our A8S table. 5et we will create a Java servlet, which will display these values in
a web browser.
The project
7e will create a simple web application, that will connect to the Derby database. 6ne Javaservlet will connect to the Derby and retrieve all data #rom the A8S table.
1 tree.]^^ build.ml]^^ contet.ml]^^ lib_ `^^ servlet-api.jar]^^ src_ `^^ Ietcode_ `^^ 'electAllCars.java
`^^ web.ml
< directories: Kiles
"n our current wor(ing directory, we have an Ant build.ml #ile, the contet.ml
con#iguration #ile, the web.ml deployment descriptor #ile, and the src and lib subdirectories.
The build.ml #ile is the Ant build #ile, which describes the tas(s to build, deploy or clean the
pro1ect. The web.ml de#ines the structure o# the web application. "n the lib directory we have
the servlet%api.1ar #ile, which is needed to compile the source #ile. ="t can be #ound in the lib
subdirectory o# the Tomcat installation directory.> "n the src directory, we have the Java
source #ile.
The web.ml #ile de#ines the structure o# the web application.
\Zml version="." encoding="3%F"ZP
\web-app mlns="http//java.sun.com/ml/ns/javaee" mlnssi="http//www.w<.org//RM5'chema-instance" sischema5ocation="http//java.sun.com/ml/ns/javaee http//java.sun.com/ml/ns/javaee/web-appE<E.sd" version="<." metadata-complete="true"P
\descriptionP 'ervlet which connects to Derby
C
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 58/68
\/descriptionP \display-namePDerby: %omcat\/display-nameP
\servletP \servlet-nameP'electAllCars\/servlet-nameP \servlet-classPIetcode.'electAllCars\/servlet-classP
\/servletP
\servlet-mappingP \servlet-nameP'electAllCars\/servlet-nameP \url-patternP/'electAllCars\/url-patternP \/servlet-mappingP
\/web-appP
These are the contents o# the the web.ml #ile. "n this #ile, we register the SelectAllars
servlet.
\Zml version="." encoding="3%F-"ZP\ContetP \#esource name="jdbc/testdb"
auth="Container" type="java.s2l.Data'ource"
username="user"password="<Bl2,"driverClass+ame="org.apache.derby.jdbc.ClientDriver"
url="jdbcderby//localhost0/testdb" maActive=""
ma6dle=""/P
\/ContetP
"n the contet.ml #ile, we de#ine the JDB datasource. The contet.ml #ile can be de#ined
#or all web applications or #or a single application. The latter is our case.
7e will show the Ant build #ile which will be used to build and deploy our tiny application.
\Zml version="." ZP
\project name="allcars" deKault="deploy"P
\property name="src.dir" value="src"/P
\property name="build.dir" value="build"/P \property name="dist.dir" value="dist"/P \property name="deploy.dir"value="/home/janbodnar/bin/tomcat/webapps"/P
\echoP1Vant.project.nameX\/echoP
\target name="init"P \mBdir dir="1Vbuild.dirX/classes" /P \mBdir dir="1Vdist.dirX"/P \echoPDirectories created.\/echoP \/targetP
\target name="compile" depends="init"P \javac srcdir="1Vsrc.dirX" destdir="1Vbuild.dirX/classes"
CI
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 59/68
includeantruntime="Kalse"P \classpath path="lib/servlet-api.jar"/P
\/javacP \echoP'ource Kiles compiled.\/echoP \/targetP
\target name="archive" depends="compile"P \war destKile="1Vdist.dirX/1Vant.project.nameX.war"webml="web.ml"P \classes dir="1Vbuild.dirX/classes"/P \metainK Kile="contet.ml"/P \/warP \echoPArchive created.\/echoP \/targetP
\target name="deploy" depends="archive"P \copy Kile="1Vdist.dirX/1Vant.project.nameX.war" todir="1Vdeploy.dirX"/P \echoP7roject deployed.\/echoP
\/targetP\target name="clean"P
\delete dir="1Vdist.dirX"/P \delete dir="1Vbuild.dirX"/P \echoP7roject cleaned.\/echoP \/targetP \/projectP
The build #ile comprises #ive tas(s. The initiali9ation tas( will create the necessary
directories. The compile tas( will compile the source code. The archive tas( will create a web
archive. The deploy tas( will deploy the archive to the Tomcat server. 0inally, the clean tas(
will do the cleaning.
The #ollowing is the SelectAllars servlet.
pacBage Ietcode!
import java.io.6>$ception!import java.io.7rintLriter!import java.s2l.Connection!import java.s2l.#esult'et!
import java.s2l.'S5$ception!import java.s2l.'tatement!import java.util.logging.5evel!import java.util.logging.5ogger!import java.naming.Contet!import java.naming.6nitialContet!import java.naming.+aming$ception!import java.servlet.'ervlet$ception!import java.servlet.http.ttp'ervlet!import java.servlet.http.ttp'ervlet#e2uest!import java.servlet.http.ttp'ervlet#esponse!import java.s2l.Data'ource!
public class 'electAllCars etends ttp'ervlet V
C*
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 60/68
protected void process#e2uest(ttp'ervlet#e2uest re2uest: ttp'ervlet#esponse response throws 'ervlet$ception: 6>$ception V
response.setContent%ype("tet/html!charset=3%F-"!
7rintLriter out = null! Connection con = null! 'tatement st = null! #esult'et rs = null!
try V
out = response.getLriter(!
Contet ct = new 6nitialContet(! Data'ource ds = (Data'ourcect.looBup("javacomp/env/jdbc/testdb"!
con = ds.getConnection(! st = con.create'tatement(!
out.println("\htmlP"! out.println("\headP"! out.println("\titleP'imple'ervlet\/titleP"! out.println("\/headP"! out.println("\bodyP"!
rs = st.eecuteSuery("'$5$C% , F#>M CA#'"!
while (rs.net( V out.print(rs.get6nt(!
out.print(" "! out.print(rs.get'tring(! out.print(" "! out.print(rs.get'tring(<! out.print("\brP"! X
out.println("\/bodyP"! out.println("\/htmlP"!
X catch (+aming$ception Q 'S5$ception e V
5ogger lgr = 5ogger.get5ogger('electAllCars.class.get+ame(! lgr.log(5evel.'$;$#$: e.getMessage(: e!
X Kinally V
try V iK (rs Y= null V rs.close(! X
iK (con Y= null V con.close(! X
iK (out Y= null V out.close(! X
+
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 61/68
X catch ('S5$ception e V
5ogger lgr =5ogger.get5ogger('electAllCars.class.get+ame(! lgr.log(5evel.LA#+6+G: e.getMessage(: e! X
X X
[>verride protected void doGet(ttp'ervlet#e2uest re2uest: ttp'ervlet#esponse response throws 'ervlet$ception: 6>$ception V process#e2uest(re2uest: response! X
[>verride protected void do7ost(ttp'ervlet#e2uest re2uest: ttp'ervlet#esponse response
throws 'ervlet$ception: 6>$ception V process#e2uest(re2uest: response! XX
"n the above servlet, we connect to the Derby testdb database and #etch all rows #rom the
A8S table.
Contet ct = new 6nitialContet(!Data'ource ds = (Data'ource ct.looBup("javacomp/env/jdbc/testdb"!
7e use the J5D" naming loo(up to obtain the datasource. 0rom the datasource, we create the
connection ob1ect.
rs = st.eecuteSuery("'$5$C% , F#>M CA#'"!
while (rs.net( V out.print(rs.get6nt(! out.print(" "! out.print(rs.get'tring(! out.print(" "! out.print(rs.get'tring(<! out.print("\brP"!X
7e use the SQL statement to retrieve all data #rom the A8S table. 7e print the data #rom
the result set ob1ect.
1 ant4uildKile /home/janbodnar/programming/derby/servlet/build.ml )echo* allcars
init )mBdir* Created dir/home/janbodnar/programming/derby/servlet/build/classes )mBdir* Created dir /home/janbodnar/programming/derby/servlet/dist )echo* Directories created.
compile
+)
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 62/68
)javac* Compiling source Kile to /home/janbodnar/programming/derby/servlet/build/classes )echo* 'ource Kiles compiled.
archive )war* 4uilding war
/home/janbodnar/programming/derby/servlet/dist/allcars.war )echo* Archive created.
deploy )copy* Copying Kile to /home/janbodnar/bin/tomcat/webapps )echo* 7roject deployed.
4365D '3CC$''F35%otal time second
7e launch the ant to build and deploy the pro1ect.
0igure 6utput o# the SelectAllars servlet
7e navigate to the localhostIIallcarsSelectAllars url and receive the output.
"n the chapter, we have wor(ed with Derby and Apache Tomcat.
Derby 'ith etbeans"n this chapter, we will wor( with the Derby database inside the 5etbeans "D3. 5etbeans has
a built%in support #or the Derby database in its basic Java S3 bundle.
So #ar we have wor(ed with the Apache Derby distribution. "n this chapter, we will wor(
with Java DB. "t is the same database, only under a di##erent name. Java DB is shipped with
Java distribution #rom Java + version.
+$
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 63/68
0igure 5etbeans services window
"n the Services window, we epand the Databases node. 7e can see two nodes. The Java DB
node and the Drivers node. "n the Java DB node we have all databases. "n the drivers node,
we can see various JDB drivers that we can use to connect to 8DB'S. These database
drivers come with the 5etbeans "D3. 7e have Java DB drivers #or both embedded and server
modes.
0igure Java DB !roperties 7indow
The above #igure is the Java DB !roperties dialog window. The window is shown when we
right clic( on the Java DB node and select the !roperties option. "n this dialog we can set two
important settings. The Java DB "nstallation directory and the Java DB system directory.
"reating a database
0irst thing to do is to create a new database. 7e will create testdb database.
+&
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 64/68
0igure Java DB contet menu
7hen we right clic( on the Java DB node, a contet menu appears. "t has #our options. Start
server, Stop server, reate Database and !roperties. 7e choose the reate Database item to
create a new database.
0igure reate Java DB Database dialog
A dialog pops up. "n this dialog window we provide a database name, user name and
password. 5ote the database location string. "t is the Java DB system directory, where our
database #iles will be created. The de#ault Java DB system directory is the .netbeans%derby
directory located in the home directory.
0igure 5ew database created
At this moment, we have a new database created. "t is visually indicated by a new database
icon under the Java DB node.
Database connection
A#ter the database is created, we create a database connection.
+/
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 65/68
5etbeans uses these icons #or connection ob1ects. The #irst icon is #or disconnected database
connection ob1ect, the second #or an established database connection ob1ect.
The above connection is a Java DB connection created with a Java DB server driver. 5otethat when we have created the testdb database, a Java DB server was automatically started
and a connection created. 5ew database connections can be created by right clic(ing on the
Java DB driver and choosing the onnect ;sing option.
7e are going to create an embedded Java DB database connection. Be#ore creating the
connection, we need to stop the Java DB server, i# it is running. Java DB database cannot be
booted by a Java DB server and connected to by an embedded driver at the same time. 5ote
that we did not have to start the server eplicitly. The server could be started behind the
scenes. 0or eample by connecting to the Java DB server connection ob1ect or creating a new
database.
0igure Stopping the server
7e clic( on the Java DB node with a right mouse button. "# the Stop Server option is enabled
it means that the server is running. 7e select it to stop the server.
0igure reating embedded connection
To create an embedded connection, we right clic( on Java DB 3mbedded driver and selectthe onnect ;sing option. Similarly, we create a server connection by choosing a Java DB
Server driver.
+C
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 66/68
0igure 5ew connection wi9ard
7e have a 5ew onnection 7i9ard dialog. "n this dialog, we #ill in the database name and
user credentials. The JDB url is created #rom this data. 7e have speci#ied the #ull path to
the testdb database. The Java DB system directory seems not to be ta(en into account here.
A#ter succes#ully creating the embedded database connection, we see the above icon in the 5etbeans Services window.
"reating a table
The database connection is created. The net thing we do is to create a new database table.
7e will create a simple table called 08"35DS with two columns. "d and 5ame. The "d will
be "5T3F38 and 5ame 4A8:A8=&>.
7e epand the Database onnection node and #urther epand the ;S38)$ schema. 7e right
clic( on the Table icon and choose reate Table option.
0igure reating a new table
A reate Table dialog appears. 7e create two columns. "d and 5ame.
++
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 67/68
0igure 0riends table created
A 08"35DS table has been created. 5ow the Tables node is epandable and we see a new
table icon.
0igure 3ecuting a command
5et we are going to eecute some SQL statements. 7e right clic( on the 08"35DS table
icon and select 3ecute ommand option. A new SQL ommand window appears in
5etbeans.
+
8/13/2019 ZetCode Apache Derby Tutorial
http://slidepdf.com/reader/full/zetcode-apache-derby-tutorial 68/68
0igure "nserting data into the 08"35DS table
"n the SQL ommand window we write several "5S38T "5T6 SQL statements. 7e eecute
the statements by clic(ing on the 8un SQL icon. The icon is a brown oval ob1ect with a green
triangle. 7e can eecute SQL statements with a trl ? Shi#t ? 3 shortcut too.
0igure 4iewing 08"35DS data
8unning S3L3T O 086' 08"35DS in the SQL ommand window we see a new window
pop up. "n this window we have a table widget with our data organi9ed in columns and rows.
7e have icons to modi#y data in this gui component.
The above picture shows the icons to wor( with the data in the table. The #irst two icons are
used to insert a new record and delete a selected record, respectively. 7e can delete multiple
records i# we select more rows with a mouse pointer and pressing the Shi#t (ey
simultaneously. "# the data was modi#ied, the ommit 8ecord=s> icon is enabled. The data is
saved only a#ter we commit it with this action. 3cept #or the SQL statements, we can modi#y
data with F;" tools. By double clic(ing on a record a line widget appears. "n this widget, we
can change the data. The changes are saved by clic(ing on the ommit 8ecord=s> action.