【发布时间】:2016-02-09 19:47:04
【问题描述】:
据我所知,我们使用 Mysql-connector jar 将 java 应用程序连接到数据库。我正在关注春季教程,并且上述内容都是通过 maven 添加的。两者有什么区别?
【问题讨论】:
标签: spring jdbc spring-jdbc mysql-connector
据我所知,我们使用 Mysql-connector jar 将 java 应用程序连接到数据库。我正在关注春季教程,并且上述内容都是通过 maven 添加的。两者有什么区别?
【问题讨论】:
标签: spring jdbc spring-jdbc mysql-connector
MySQL 连接器是一个允许 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);
看看一种方法是如何少得多的?
【讨论】: