Database Reference
In-Depth Information
%
java Connect
Connected
Disconnected
You might need to set your
CLASSPATH
environment variable before the example pro‐
gram will compile and run. The value of
CLASSPATH
should include at least your current
directory (
.
) and the path to the Connector/J JDBC driver. For background on running
Java programs or setting
CLASSPATH
, read “Executing Programs from the Command
Line” on the companion website (see the
Preface
).
The
import
java.sql.*
statement references the classes and interfaces that provide
access to the data types used to manage different aspects of your interaction with the
database server. These are required for all JDBC programs.
Connecting to the server is a two-step process. First, register the database driver with
JDBC by calling
Class.forName()
. The
Class.forName()
method requires a driver
name; for Connector/J, use
com.mysql.jdbc.Driver
. Then call
DriverManager.get
Connection()
to initiate the connection and obtain a
Connection
object that maintains
information about the state of the connection. Java programs in this topic conventionally
use
conn
to signify connection objects.
DriverManager.getConnection()
takes three arguments: a URL that describes where
to connect and the database to use, the MySQL username, and the password. The URL
string has this format:
jdbc:
driver
://
host_name
/
db_name
This format follows the Java convention that the URL for connecting to a network
resource begins with a protocol designator. For JDBC programs, the protocol is
jdbc
,
and you'll also need a subprotocol designator that specifies the driver name (
mysql
, for
MySQL programs). Many parts of the connection URL are optional, but the leading
protocol and subprotocol designators are not. If you omit
host_name
, the default host
value is
localhost
. To select no default database, omit the database name. However,
you should not omit any of the slashes in any case. For example, to connect to the local
host without selecting a default database, the URL is:
jdbc:mysql:///
In JDBC, you don't test method calls for return values that indicate an error. Instead,
provide handlers to be called when exceptions are thrown.
Recipe 2.2
discusses error
handling further.