Java Reference
In-Depth Information
Beforeyoucancommunicatewithadatasource,youneedtoestablishaconnection.
JDBC provides the java.sql.DriverManager class and the
javax.sql.DataSource interface for this purpose:
DriverManager letsanapplicationconnecttoadatasourcebyspecifyinga
URL. When this class first attempts to establish a connection, it automatically
loads any JDBC 4.x drivers located via the classpath. (Pre-JDBC 4.x drivers
must be loaded manually.)
DataSource hides connection details from the application to promote data
sourceportabilityandispreferredover DriverManager forthisreason.Be-
cause a discussion of DataSource is somewhat involved (and is typically
used in a Java EE context), I focus on DriverManager in this chapter.
Before letting you obtain a data source connection, early JDBC versions required
you to explicitly load a suitable driver, by specifying Class.forName() with the
name of the class that implements the Driver interface. For example, the JDBC-
ODBC Bridge driver was loaded via
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); . Later JDBC ver-
sions relaxed this requirement by letting you specify a list of drivers to load via the
jdbc.drivers systemproperty. DriverManager wouldattempttoloadallthese
drivers during its initialization.
Under Java 7, DriverManager first loads all drivers identified by the jd-
bc.drivers system property. It then uses the java.util.ServiceLoader -
based service provider mechanism (discussed in Appendix C) to load all drivers from
accessibledriverJARfilessothatyoudon'thavetoexplicitlyloaddrivers.Thismech-
anism requires a driver to be packaged into a JAR file that includes META-INF/
services/java.sql.Driver .The java.sql.Driver textfilemustcontaina
single line that names the driver's implementation of the Driver interface.
Each loaded driver instantiates and registers itself with DriverManager via
DriverManager 's void registerDriver(Driver driver) classmethod.
When invoked, a getConnection() method walks through registered drivers, re-
turning an implementation of the java.sql.Connection interface from the first
driver that recognizes getConnection() 's JDBC URL. (You might want to check
out DriverManager 's source code to see how this is done.)
Note Tomaintaindatasource-independence,muchofJDBCconsistsofinterfaces.
Each driver provides implementations of the various interfaces.
Search WWH ::




Custom Search