Java在try-with-resources中准备好的语句不能正常工作
发布时间:2020-12-14 05:37:01 所属栏目:Java 来源:网络整理
导读:参见英文答案 How should I use try-with-resources with JDBC?4个 昨天Stack上的多个人推荐使用try-with-resources.我正在为我的所有数据库操作执行此操作.今天我想将Statement更改为PreparedStatement以使查询更安全.但是,当我尝试在try-with-resources中
参见英文答案 >
How should I use try-with-resources with JDBC?4个
昨天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)资源. Connection,PreparedStatement和ResultSet是Autoclosable,所以没关系.
但是stmt.setInt(1,user)不是资源,而是一个简单的语句.在try-with-resource语句中不能有简单的语句(不是资源声明)! 解决方案:创建多个try-with-resource语句! try (Connection conn = DriverManager.getConnection(DBURL,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语句中,它也可以工作.我只考虑将连接管理内容与其余代码分开的良好做法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |