no *_*one 4 spring jdbc mysql-connector spring-jdbc
据我所知,我们使用 Mysql-connector jar 将 java 应用程序连接到数据库。我正在关注 spring 教程,上面提到的东西都是通过 Maven 添加的。两者有什么区别?
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) {}
}
}
Run Code Online (Sandbox Code Playgroud)
JdbcTemplate 之后:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
int count = jdbcTemplate.queryForObject("select count(*) from foo", Integer.class);
Run Code Online (Sandbox Code Playgroud)
看看一种方法如何少得多?
| 归档时间: |
|
| 查看次数: |
2467 次 |
| 最近记录: |