Use DataSource Whenever Possible
If you have a choice, you always should
use javax.sql.DataSource to get a JDBC connection.
Data sources, which were introduced with JDBC 2.0, make the job of
configuring a database connection and connecting to a database nearly
foolproof. Consider the following data source code fragment:
InitialContext ctx = new InitialContext( );
DataSource ds = (DataSource)ctx.lookup("dsname");
Connection conn = ds.getConnection( );This code contains nothing proprietary, involves no parsing of configuration files, and uses no information dependent on the deployment environment other than a data source name. Now, compare that code to the following:
Connection conn;
Class.forName("org.gjt.mm.mysql.Driver").newInstance( );
conn = DriverManager.getConnection("jdbc:mysql://carthage:/db", "user", "password");This code is the simplest alternative to using a data source.
However, the latter example is harder to read, contains proprietary
code (i.e., specific reference to the
Driver
implementation class, which is the JDBC URL for a specific driver),
and requires hard-coded information about the runtime environment
(e.g., the host and database in the URL, the username, and the
password). In short, you have to compile the
DriverManager version
for a specific target runtime environment.
To be fair, it is possible to achieve the same level of portability with the driver manager approach as with the data source approach. However, doing so makes your application code ...