GreyPompom / sistema_emprestimo_A3

Projeto de sistema de emprestimo, em JAVA-MVC com interfaces.
MIT License
2 stars 0 forks source link

Uso Incorreto do res.next(); em FerramentaDAO e AmigoDAO #57

Open PoweredTable opened 3 months ago

PoweredTable commented 3 months ago

Descrição

Nas classes FerramentaDAO e AmigoDAO, há um uso inadequado do método res.next(); em algumas partes do código. Este método é responsável por mover o cursor do ResultSet para a próxima linha, retornando true se houver uma linha seguinte e false se não houver. No entanto, em certos trechos do código, res.next(); está sendo chamado sem verificar se realmente há uma linha disponível no ResultSet, o que pode levar a exceções e comportamentos inesperados.

Código com Problema

Classe FerramentaDAO

  1. Método pegaMaiorID:
public int pegaMaiorID() throws SQLException {
    int maior = 0;
    try {
        Connection conexao = ConexaoDB.getConexao();
        if (conexao != null) {
            try (Statement stmt = conexao.createStatement()) {
                ResultSet res = stmt.executeQuery("SELECT MAX(id_ferramenta) id_ferramenta FROM ferramentas");
                res.next();  // Problema: Não verifica se há uma linha disponível.
                maior = res.getInt("id_ferramenta");
            }
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    return maior;
}
  1. Método carregaFerramenta:
public Ferramenta carregaFerramenta(int id) {
    Ferramenta objeto = new Ferramenta();
    objeto.setId(id);
    try {
        Connection conexao = ConexaoDB.getConexao();
        if (conexao != null) {
            try (Statement stmt = conexao.createStatement()) {
                ResultSet resposta = stmt.executeQuery("SELECT * FROM ferramentas WHERE id_ferramenta = " + id);
                resposta.next();  // Problema: Não verifica se há uma linha disponível.
                objeto.setNome(resposta.getString("nome"));
                objeto.setMarca(resposta.getString("marca"));
                objeto.setCusto(resposta.getDouble("custo_aquisicao"));
            }
        }
    } catch (SQLException erro) {
    }
    return objeto;
}

Classe AmigoDAO

  1. Método pegaMaiorID:
public int pegaMaiorID() throws SQLException {
    int maior = 0;
    try {
        Connection conexao = ConexaoDB.getConexao();
        if (conexao != null) {
            try (Statement stmt = conexao.createStatement()) {
                ResultSet res = stmt.executeQuery("SELECT MAX(id_amigo) id_amigo FROM amigos");
                res.next();  // Problema: Não verifica se há uma linha disponível.
                maior = res.getInt("id_amigo");
            }
        }
    } catch (SQLException ex) {
    }
    return maior;
}
  1. Método carregaAmigo:
public Amigo carregaAmigo(int id) {
    Amigo objeto = new Amigo();
    objeto.setId(id);
    try {
        Connection conexao = ConexaoDB.getConexao();
        if (conexao != null) {
            try (Statement stmt = conexao.createStatement()) {
                ResultSet resposta = stmt.executeQuery("SELECT * FROM amigos WHERE id_amigo = " + id);
                resposta.next();  // Problema: Não verifica se há uma linha disponível.
                objeto.setNome(resposta.getString("nome"));
                objeto.setTelefone(resposta.getString("telefone"));
            }
        }
    } catch (SQLException erro) {
        throw new RuntimeException(erro);
    }
    return objeto;
}

Problemas

Correção na Classe FerramentaDAO

  1. Método pegaMaiorID:
public int pegaMaiorID() throws SQLException {
    int maior = 0;
    try {
        Connection conexao = ConexaoDB.getConexao();
        if (conexao != null) {
            try (Statement stmt = conexao.createStatement()) {
                ResultSet res = stmt.executeQuery("SELECT MAX(id_ferramenta) id_ferramenta FROM ferramentas");
                if (res.next()) {
                    maior = res.getInt("id_ferramenta");
                }
            }
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    return maior;
}
  1. Método carregaFerramenta:
public Ferramenta carregaFerramenta(int id) {
    Ferramenta objeto = new Ferramenta();
    objeto.setId(id);
    try {
        Connection conexao = ConexaoDB.getConexao();
        if (conexao != null) {
            try (Statement stmt = conexao.createStatement()) {
                ResultSet resposta = stmt.executeQuery("SELECT * FROM ferramentas WHERE id_ferramenta = " + id);
                if (resposta.next()) {
                    objeto.setNome(resposta.getString("nome"));
                    objeto.setMarca(resposta.getString("marca"));
                    objeto.setCusto(resposta.getDouble("custo_aquisicao"));
                }
            }
        }
    } catch (SQLException erro) {
    }
    return objeto;
}

Correção na Classe AmigoDAO

  1. Método pegaMaiorID:
public int pegaMaiorID() throws SQLException {
    int maior = 0;
    try {
        Connection conexao = ConexaoDB.getConexao();
        if (conexao != null) {
            try (Statement stmt = conexao.createStatement()) {
                ResultSet res = stmt.executeQuery("SELECT MAX(id_amigo) id_amigo FROM amigos");
                if (res.next()) {
                    maior = res.getInt("id_amigo");
                }
            }
        }
    } catch (SQLException ex) {
    }
    return maior;
}
  1. Método carregaAmigo:
public Amigo carregaAmigo(int id) {
    Amigo objeto = new Amigo();
    objeto.setId(id);
    try {
        Connection conexao = ConexaoDB.getConexao();
        if (conexao != null) {
            try (Statement stmt = conexao.createStatement()) {
                ResultSet resposta = stmt.executeQuery("SELECT * FROM amigos WHERE id_amigo = " + id);
                if (resposta.next()) {
                    objeto.setNome(resposta.getString("nome"));
                    objeto.setTelefone(resposta.getString("telefone"));
                }
            }
        }
    } catch (SQLException erro) {
        throw new RuntimeException(erro);
    }
    return objeto;
}

Conclusão

A adição da verificação if (res.next()) garante que o código somente tente acessar os dados se houver uma linha disponível no ResultSet. Essa modificação torna o código mais robusto e evita possíveis exceções e inconsistências.

https://chatgpt.com/share/fa7cc03d-54f2-4d7a-a31f-4784fcf01afd