Consider the following five methods:
Which method should you use to connect to a java Db database with JDBC 4.0, but not with
previous versions of JDBC?
A.
getConnectionA
B.
getConnectionB
C.
getConnectionC
D.
getConnectionD
E.
getConnectionE
Explanation:
Note on D not E: Prior to JDBC 4.0, we relied on the JDBC URL to define a data
source connection. Now with JDBC 4.0, we can get a connection to any data source by simply
supplying a set of parameters (such as host name and port number) to a standard connection
factory mechanism. New methods were added to Connection and Statement interfaces to permit
improved connection state tracking and greater flexibility when managing Statement objects in
pool environments.
Note on that an embedded driver is no longer needed(not A, B, C):
Thanks to the Java SE Service Provider mechanism included in Mustang, Java developers no
longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC
driver. The DriverManager class takes care of this by automatically locating a suitable driver when
the DriverManager.getConnection() method is called. This feature is backward-compatible, so no
changes are needed to the existing JDBC code.
In JDBC 4.0, we no longer need to explicitly load JDBC drivers using Class.forName(). When the
method getConnection is called, the DriverManager will attempt to locate a suitable driver from
among the JDBC drivers that were loaded at initialization and those loaded explicitly using the
same class loader as the current application.
Assume that we need to connect to an Apache Derby database, since we will be using this in the
sample application explained later in the article:
Class.forName(“org.apache.derby.jdbc.EmbeddedDriver”);
Connection conn =
DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
But in JDBC 4.0, we don’t need the Class.forName() line. We can simply call getConnection() to
get the database connection.