O'Reilly logo

Java Enterprise in a Nutshell, Second Edition by David Flanagan, Jim Farley, William Crawford

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The JDBC Optional Package

The javax.sql package is an optional extension of the JDBC 2.1 API. It includes support for a variety of enterprise-development activities. It’s a standard component of the J2EE platform, and the supporting classes can also be downloaded separately for use with any Java 2 system.

DataSource Objects

The DataSource interface provides an alternative to the DriverManager class and conventional JDBC URLs. Instead, information about a database is stored within a naming service and retrieved via the JNDI API. Connection information (drivers, server locations, and so forth) are stored within the DataSource object, which uses them to create the actual Connection object used to execute JDBC commands. DataSource objects are also used to provide native driver-level support for connection pooling and distributed transactions.

Each DataSource is assigned a logical name, by convention beginning with “jdbc/”. The logical name and associated connection metadata are configured in the J2EE setup process. This makes code more portable and allows for easy changes in drivers and connection information. Accessing a DataSource via JNDI is very simple:

Context ctx = new InitialContext(  ); 
DataSource ds = (DataSource)ctx.lookup("jdbc/CamelDB"); 
Connection con = ds.getConnection("lawrence", "arabia");

The first two lines obtain the DataSource object from the naming service. The getConnection( ) method of DataSource then logs into the database and returns a Connection object. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required