这实际上是资源泄漏吗?

时间:2016-03-25 01:10:40

标签: java mysql

我有一个"邀请"在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);
    }

}

1 个答案:

答案 0 :(得分:4)

我认为泄漏是在第一份准备好的声明中。

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