昨天有多个Stack上的人推荐使用try-with-resources。现在我已经对所有数据库操作都采用这种方式。今天我想将Statement更改为PreparedStatement以使查询更加安全。但是当我尝试在try-with-resources中使用预编译语句时,我一直收到错误信息,例如'identifier expected'或';'或')'。
我做错了什么?还是不可能实现?这是我的代码:
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE id = ? LIMIT 1");
stmt.setInt(1, user);
ResultSet rs = stmt.executeQuery()) {
// if no record found
if(!rs.isBeforeFirst()) {
return false;
}
// if record found
else {
return true;
}
} catch (SQLException e) {
// log error but dont do anything, maybe later
String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;
}