Friday, April 13, 2007

Best Practices for Accessing a Database Through Java

I noted this down from a forum somewhere:

My personal opinion is that it is not the responsibility of a connection
pool to make up for application developer screw-ups. App developers can
make nearly all of this kind of problem go away if they would follow a
very simple design pattern:


DataSource ds = ...; // Acquire a reference to your connection pool
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = ds.getConnection();
... use "conn" to do some database access stuff ...
... passing the "conn" instance to any subordinate methods ...
... that need access to this connection ...
} catch (SQLException e) {
... deal with database errors ...
} finally {
if (conn != null) {
try {
conn.close(); // Return connection to the pool
} catch (SQLException e) {
... report a really bad problem ...
}
}

You can extend this to cleaning up open Statement and/or ResultSet objects

No comments:

Labels

Blog Archive

Contributors