Skip to Main Content
Java Enterprise Best Practices
book

Java Enterprise Best Practices

by O'Reilly Java Authors
December 2002
Intermediate to advanced content levelIntermediate to advanced
288 pages
9h 46m
English
O'Reilly Media, Inc.
Content preview from Java Enterprise Best Practices

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Moving to Java 9: Better Design and Simpler Code

Moving to Java 9: Better Design and Simpler Code

Trisha Gee
Java EE 8 High Performance

Java EE 8 High Performance

Romain Manni-Bucau

Publisher Resources

ISBN: 0596003846Supplemental ContentErrata Page