The following code works fine:
String connStr = "jdbc:mysql://localhost:3306/addressbook";
try ( Connection conn = DriverManager.getConnection(connStr, "root", "");
PreparedStatement ps = conn.prepareStatement("select * from contact where firstName=?");
) {
ps.setString(1, "Cippo");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
System.out.print(rs.getString(2) + "\t");
System.out.print(rs.getString(3) + "\t");
System.out.print(rs.getInt(1) + "\t");
System.out.print(rs.getString(4) + "\t");
System.out.println(rs.getString(5));
}
} catch (SQLException e) {
e.printStackTrace();
System.exit(-1);
}
But for a mysterious reason when I move other two instructions into the try-with-resource block (where they are supposed to stay), I get a compilation error:
String connStr = "jdbc:mysql://localhost:3306/addressbook";
try ( Connection conn = DriverManager.getConnection(connStr, "root", "");
PreparedStatement ps = conn.prepareStatement("select * from contact where firstName=?");
ps.setString(1, "Cippo");
ResultSet rs = ps.executeQuery();
) {
while(rs.next()) {
System.out.print(rs.getString(2) + "\t");
System.out.print(rs.getString(3) + "\t");
System.out.print(rs.getInt(1) + "\t");
System.out.print(rs.getString(4) + "\t");
System.out.println(rs.getString(5));
}
} catch (SQLException e) {
e.printStackTrace();
System.exit(-1);
}
The compilation error is irreasonable: "ps cannot be resolved". But conn is resolved without any problem. Why that?