【发布时间】:2014-09-15 22:09:04
【问题描述】:
昨天 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;
}
【问题讨论】:
-
在第一行,将
;更改为) {。 (愚蠢的错字?)
标签: java sql prepared-statement