我有一个在MySQL数据库中建模的“邀请”对象。该对象具有一个列表(“ treatmentPlanIDsToCopyf”),并通过第二个表保留在数据库中。我编写的插入到主表中,然后遍历列表并将列表中每个项目的记录插入第二个表的方法如下。在ps = cn.prepareStatement(sql);行上,Eclipse给我一个警告,指出“资源泄漏:'ps'在此位置未关闭”。我正在关闭finally子句中的准备好的语句,所以我想知道是否确实需要修复资源泄漏。这是我第一次使用带有预准备语句的批处理,因此我不确定。谢谢。

public void invitationCreate(Connection cn, Invitation invitation) throws SQLException{

    PreparedStatement ps = null;

    try {
        //first insert primary invitation data into the invitation table
        String sql = "INSERT INTO invitiation (invitation_code, recipient_email, sender_user_id_fk, date_intived, date_accepted, accepted, recipient_first_name, recipient_last_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

        ps = cn.prepareStatement(sql);

        ps.setString(1, invitation.getInvitationCode());
        ps.setString(2, invitation.getRecipientEmail());
        ps.setInt(3, invitation.getSenderUserID());
        ps.setTimestamp(4, convertLocalTimeDateToTimstamp(invitation.getDateInvited()));
        ps.setTimestamp(5, convertLocalTimeDateToTimstamp(invitation.getDateAccepted()));
        ps.setBoolean(6, invitation.isAccepted());
        ps.setString(7, invitation.getRecipientFirstName());
        ps.setString(8, invitation.getRecipientLastName());

        int success = ps.executeUpdate();

        //now loop through all the treatmentPlanIDs in the invitation that are to be copied into the invitees account when the register

        sql = "INSERT INTO invitation_treatment_plans (invitation_code_fk, invitation_treatment_plan_id_fk) VALUES (?, ?)";

        ps = cn.prepareStatement(sql);//TODO confirm this if this is actually a resource leak

        for(int treatmentPlanID : invitation.getTreatmentPlanIDsToCopy()){
            ps.setString(1, invitation.getInvitationCode());
            ps.setInt(2, treatmentPlanID);

            ps.addBatch();
        }

        ps.executeBatch();

    } finally {
        DbUtils.closeQuietly(ps);
    }

}

最佳答案

我相信泄漏是在第一个准备好的声明中。

int success = ps.executeUpdate();之后,您需要先关闭该准备好的语句,然后再将变量分配给新的准备好的语句。

关于java - 这实际上是资源泄漏吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36212579/

10-11 22:34
查看更多