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

Get Java Enterprise in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.