Friday, April 9, 2010

How to use a DataSource

In this post, we'll use the DataSource that is configured in the previous post.

Get the initial JNDI context object, which provides access to the JNDI interface of the application server.

Context ctext = new InitialContext();

Now, use the logical name that is configured in the application server to retrieve the datasource.

DataSource ds =
(DataSource)ctext.lookup("jdbc/<logical_name>");

Get the connection from the pool. The two parameters are optional. The default credentials are used by the application server, when the parameters are omitted.

Connection conn = ds.getConnection("<username>","<password>");

Use the connection.

PreparedStatement stmt = conn.prepareStatement(
"UPDATE table SET int_col=? WHERE varchar_col=?");
stmt.setInt(1, 75);
stmt.setString(2, "condition");
stmt.executeUpdate():

Finally, return the connection to the pool.

conn.close();

No comments:

Post a Comment