One really simple approach is to use Spring's JDBC classes, which provide a lot of convenience methods over raw JDBC and automatically manage the releasing of resources. Spring also provides a rich exception hierarchy, which allows specific actions to be taken based on specific errors (e.g. retry on database deadlock).
Also, unlike many other persistence layers Spring does not hide the JDBC implementation under the covers (it acts as a thin layer), allowing you to use raw JDBC if necessary.
Initialisation
// First create a DataSource corresponding to a single connection.
// Your production application could potentially use a connection pool.
// true == suppress close of underlying connection when close() is called.
DataSource ds = new SingleConnectionDataSource("com.MyDriver", "Database URL", "user", "password", true);
// Now create a SimpleJdbcTemplate passing in the DataSource. This provides many
// useful utility methods.
SimpleJdbcTemplate tmpl = new SimpleJdbcTemplate(ds);
SQL Update (or Insert)
// Simple example of SQL update. The resources are automatically release if an exception
// occurs. SQLExceptions are translated into Spring's rich DataAccessException exception
// hierarchy, allowing different actions to be performed based on the specific type of
// error.
int nRows = tmpl.update("update Foo set Name = ? where Id = ?", "Hello", 5);
assert nRows == 1;
SQL Query
// Example of SQL query using ParameterizedRowMapper to translate each row of the
// ResultSet into a Person object.
tmpl.query("select * from Person", new ParameterizedRowMapper<Person>() {
Person mapRow(ResultSet rs, int rowNum) {
return new Person(rs.getString("FirstName"), rs.getString("LastName"));
}
});