Tag: 试用资源

Java 7自动资源pipe理JDBC(试用资源语句)

如何整合创build/接收连接的常见JDBC习惯用法,查询数据库并可能使用Java 7的自动资源pipe理,try-with-resources声明处理结果? ( 教程 ) 在Java 7之前,通常的模式是这样的: Connection con = null; PreparedStatement prep = null; try{ con = getConnection(); prep = prep.prepareStatement("Update …"); … con.commit(); } catch (SQLException e){ con.rollback(); throw e; } finally{ if (prep != null) prep.close(); if (con != null) con.close(); } 有了Java 7,你可以去: try(Connection con = getConnection(); PreparedStatement prep = con.prepareConnection("Update […]

我是否正确使用了Java 7的try-with-resources

我期待缓冲的阅读器和文件阅读器closures,并释放资源,如果抛出exception。 public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException { try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { return read(br); } } 但是,是否有要求成功closures的catch条款? 编辑: 从本质上讲,Java 7中的上述代码等同于下面的Java 6: public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filePath)); return read(br); } catch (Exception ex) { throw […]

我应该如何在JDBC中使用try-with-resources?

我有一个使用JDBC从数据库中获取用户的方法: public List<User> getUser(int userId) { String sql = "SELECT id, name FROM users WHERE id = ?"; List<User> users = new ArrayList<User>(); try { Connection con = DriverManager.getConnection(myConnectionURL); PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, userId); ResultSet rs = ps.executeQuery(); while(rs.next()) { users.add(new User(rs.getInt("id"), rs.getString("name"))); } rs.close(); ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } […]