try-with-resources 中的 Java 准备语句不起作用

标签 java sql prepared-statement

<分区>

昨天,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;

    }

最佳答案

try-with-resource 语句用于声明(Autoclosable)资源。 ConnectionPreparedStatementResultSetAutoclosable,所以没问题。

但是 stmt.setInt(1, user) 不是资源,而是一个简单的语句。在 try-with-resource 语句中不能有简单语句(不是资源声明)!

解决方案:创建多个 try-with-resource 语句!

try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS)) {
    executeStatement(conn);
} catch (SQLException e) {
    // log error but dont do anything, maybe later
    String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
    return false;
}

private void executeStatement(Connection con) throws SQLException {
    try (PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE id=? LIMIT 1")) {
        stmt.setInt(1, user);
        try (ResultSet rs = stmt.executeQuery()) {
            // process result
        }
    }
}

(请注意,从技术上讲,不需要像我那样将 SQL 语句的执行放入单独的方法中。如果打开连接和创建 PreparedStatement 两者都在同样的 try-with-resource 语句。我只是认为将连接管理内容与其余代码分开是一种很好的做法。

关于try-with-resources 中的 Java 准备语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24932262/

相关文章:

java - 有没有办法在jooq中进行反向 "code generation"?

java - MSC000001 : Failed to start service jboss. web.deployment.default-host./scWeb ..... JBAS018040:无法启动上下文

php - 我可以将数组绑定(bind)到 PDO 查询中的 IN() 条件吗?

php - prepare() 输出 bool false,语句对我来说看起来是正确的

Java SQL更新语法错误

java - 加载 Java 实体时内存不足

java - Spring Security - Autowiring 不工作

mysql - 编写查询以选择带有附加字母的列

c# - 存储过程返回 int 而不是结果集

c# - SQL语句获取一周前的数据?