Java Reference
In-Depth Information
tialContext looks at all the DataSources available within the application server
and returns a valid DataSource if it is found; otherwise, it will throw a
java.naming.NamingException exception. In Solution 2, you can see that the
InitialContext returns an object that must be casted as a DataSource .
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/myOracleDS");
If the DataSource is a connection pool cache, it will send one of the available
connections within the pool when an application requests it. The following line of code
returns a Connection object from the DataSource :
conn = ds.getConnection();
Of course, if no valid connection can be obtained, a java.sql.SQLException
is thrown. The DataSource technique is preferred over the DriverManager be-
cause database connection information is stored in only one place: the application serv-
er. Once a valid DataSource is deployed, it can be used by many applications.
After a valid connection has been obtained by your application, it can be used to
work with the database. To learn more about working with the database using a Con-
nection object, see Recipes 13-2 and 13-4.
13-2. Handling Connection and SQL Ex-
ceptions
Problem
A database activity in your application has thrown an exception. You need to handle
the SQL exception so that your application does not crash.
Solution
Use a try-catch block in order to capture and handle any SQL exceptions that are
thrown by your JDBC connection or SQL queries. The following code demonstrates
how to implement a try-catch block in order to capture SQL exceptions:
Search WWH ::




Custom Search