JDK7新增功能-利用trycatch语句自动关闭资源

可以用来关闭Scanner 等IO流


try(Scanner console=new Scanner(System.in)){
	int x= console.nextInt();
}



也可用来关闭JDBC中用到的资源


public class InsertSample2 {

	public static void main(String[] args) {
		XSB student = new XSB("191602", "李四", 0, "1998-7-9", "计算机", 0, null);

		String sql = "INSERT INTO xsb(xh, xm, xb, csrq, zy, zxf, bz) "
				   + "VALUES(?, ?, ?, ?, ?, ?, ?)";

		try (Connection con = DriverManager.getConnection(url, user, password);
				PreparedStatement pstmt = con.prepareStatement(sql)) {
			pstmt.setString(1, student.getXh());
			pstmt.setString(2, student.getXm());
			pstmt.setInt(3, student.getXb());
			pstmt.setString(4, student.getCsrq());
			pstmt.setString(5, student.getZy());
			pstmt.setInt(6, student.getZxf());
			pstmt.setString(7, student.getBz());

			int rowCount = pstmt.executeUpdate();
			System.out.println("插入" + rowCount + "行");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}


你可能感兴趣的:(J2SE)