准备语句时PreparedStatement资源泄漏

时间:2016-11-10 00:30:55

标签: java mysql prepared-statement resultset

我怀疑这可能是误报,但我不能确定,所以我有些困惑。我正在使用Eclipse Neon,问题出现在我第三次准备声明时。我在下面做了几乎相同的事情,没有错误。

try{
        Connection con = MySQL.connection;
        PreparedStatement ps = con.prepareStatement("SELECT * from UsernameData "
                + "WHERE UUID = '" + player.getUniqueId() + "'");
        ResultSet rs = ps.executeQuery();
        if(rs.next() == true){
            ps = con.prepareStatement("update UsernameData set UUID = ?, Username = ? where UUID = ?");
            ps.setString(1, uuid);
            ps.setString(2, username);
            ps.setString(3, uuid);
            ps.execute();
            ps.close();
            rs.close();
            return;
        }
        ps = con.prepareStatement("insert into UsernameData(UUID, Username)"
                + " values (?, ?)");
        ps.setString(1, uuid);
        ps.setString(2, username);
        ps.execute();
        ps.close();
        rs.close();
        return;
    }catch(SQLException e){
        Bukkit.getServer().getLogger().warning("SQL Error: " + e);
    }

1 个答案:

答案 0 :(得分:0)

当你踩踏插入map[string]interface{}时,你不会关闭第一组资源。

您还应该考虑使用try-with-resources:

ps

是的,第二个和第三个PreparedStatement可能会被浪费掉。如果您愿意,可以将它们包装在自己的try-with-resources中。

但问题的症结在于你在 try (Connection con = MySQL.connection; PreparedStatement ps = con.prepareStatement("SELECT * from UsernameData " + "WHERE UUID = '" + player.getUniqueId() + "'"); PreparedStatement ps2 = con.prepareStatement("update UsernameData set UUID = ?, Username = ? where UUID = ?"); PreparedStatement ps3 = con.prepareStatement("insert into UsernameData(UUID, Username)" + " values (?, ?)"); ResultSet rs = ps.executeQuery()) { if (rs.next() == true) { ps2.setString(1, uuid); ps2.setString(2, username); ps2.setString(3, uuid); ps2.execute(); return; } ps3.setString(1, uuid); ps3.setString(2, username); ps3.execute(); return; } catch (SQLException e) { Bukkit.getServer().getLogger().warning("SQL Error: " + e); } 变量上踩踏。