<分区>
昨天,Stack 上的多人推荐使用 try-with-resources。我现在正在为我的所有数据库操作执行此操作。今天想把Statement改成PreparedStatement,让查询更安全。但是,当我尝试在 try-with-resources 中使用准备好的语句时,我不断收到诸如“预期标识符”或“;”之类的错误或 ')'。
我做错了什么?或者这不可能吗?这是我的代码:
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;
}