Spring JDBC VS JDBC的主要区别是什么?
解决方法
让我来看一下使用JDBC的简单例子:
final Connection connection = ds.getConnection(); try { final Statement statement = connection.createStatement(); try { final ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM Orders"); try { resultSet.next(); final int c = resultSet.getInt(1); } finally { resultSet.close(); } } finally { statement.close(); } } finally { connection.close(); }
尝试使用资源的时候好多了:
try ( Connection connection = ds.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM Orders"); ) { resultSet.next(); final int c = resultSet.getInt(1); }
当然可以提取常用代码,并使用模板方法设计模式.有效地你会重新创建JdbcTemplate:
final int c = new JdbcTemplate(ds).queryForInt("SELECT COUNT(*) FROM Orders");