以下代码工作正常:
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);
}
但是由于一个神秘的原因,当我将其他两条指令移动到 try-with-resource 块(它们应该保留的位置)时,我得到了一个编译错误:
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);
}
编译错误不合理:“ps无法解析”。但是 conn 解决了没有任何问题。为什么?