Java Reference
In-Depth Information
system—that step configured a
CLASSPATH
environment variable in the command window
for your platform. After doing so, you can run this application simply using the command
java DisplayAuthors
Connecting to the Database
The JDBC interfaces we use in this example each extend the
AutoCloseable
interface, so
you can use objects that implement these interfaces with the
try
-with-resources statement
(introduced in Section 11.12). Lines 19-23 create this example's
AutoCloseable
objects
in the parentheses following keyword
try
—such objects are automatically closed when the
try
block terminates (line 43) or if an exception occurs during the
try
block's execution.
Each object created in the parentheses following keyword
try
must be separated from the
next by a semicolon (
;
).
Lines 20-21 create a
Connection
object (package
java.sql
) referenced by
connec-
tion
. An object that implements interface
Connection
manages the connection between
the Java program and the database.
Connection
objects enable programs to create SQL
statements that manipulate databases. The program initializes
connection
with the result
of a call to
static
method
getConnection
of class
DriverManager
(package
java.sql
),
which attempts to connect to the database specified by its URL.
Method
getConnection
takes three arguments
•a
String
that specifies the database URL,
•a
String
that specifies the username and
•a
String
that specifies the password.
The username and password for the
books
database were set in Section 24.5. If you used
a different username and password there, you'll need to replace the username (second ar-
gument) and password (third argument) passed to method
getConnection
in line 21.
The URL locates the database (possibly on a network or in the local file system of the
computer). The URL
jdbc:derby:books
specifies the protocol
for communication
(
jdbc
), the
subprotocol
for communication (
derby
) and the location of the database
(
books
). The subprotocol
derby
indicates that the program uses a Java DB/Apache Derby-
specific subprotocol to connect to the database—recall that Java DB is simply the Oracle
branded version of Apache Derby. If the
DriverManager
cannot connect to the database,
method
getConnection
throws a
SQLException
(package
java.sql
). Figure 24.24 lists
the JDBC driver names and database URL formats of several popular RDBMSs.
RDBMS
Database URL format
MySQL
jdbc:mysql://
hostname
:
portNumber
/
databaseName
ORACLE
jdbc:oracle:thin:@
hostname
:
portNumber
:
databaseName
DB2
jdbc:db2:
hostname
:
portNumber
/
databaseName
PostgreSQL
jdbc:postgresql://
hostname
:
portNumber
/
databaseName
Java DB/Apache Derby
jdbc:derby:
dataBaseName
(embedded)
jdbc:derby://
hostname
:
portNumber
/
databaseName
(network)
Fig. 24.24
|
Popular JDBC database URL formats. (Part 1 of 2.)