MySQL Connector是允许Java与MySQL对话的驱动程序.
Spring JDBC是一个使编写JDBC代码更容易的库. JdbcTemplate特别有用.
在JdbcTemplate之前:
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
int count;
try {
connection = dataSource.getConnection();
statement = connection.createStatement();
rs = statement.executeQuery("select count(*) from foo");
if(rs.next()) {
count = rs.getInt(0);
}
} catch (SQLException exp) {
throw new RuntimeException(exp);
} finally {
if(connection != null) {
try { connection.close(); } catch (SQLException exp) {}
}
if(statement != null) {
try { statement.close(); } catch (SQLException exp) {}
}
if(rs != null) {
try { rs.close(); } catch (SQLException exp) {}
}
}
在JdbcTemplate之后:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
int count = jdbcTemplate.queryForObject("select count(*) from foo", Integer.class);
看看一种方式吸吮少得多吗?