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
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;
}
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
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;
}
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
Exceção SQLException: Se res.next() for chamado quando o ResultSet estiver vazio, uma exceção será lançada.
Incerteza nos dados: Pode haver situações onde o código assume que há um resultado sem realmente garantir isso, o que pode levar a inconsistências.
Solução Proposta
A solução envolve adicionar uma verificação antes de acessar os dados do ResultSet. Deve-se verificar se há uma linha disponível utilizando if (res.next()).
Correção na Classe FerramentaDAO
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;
}
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
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;
}
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.
Descrição
Nas classes
FerramentaDAO
eAmigoDAO
, há um uso inadequado do métodores.next();
em algumas partes do código. Este método é responsável por mover o cursor doResultSet
para a próxima linha, retornandotrue
se houver uma linha seguinte efalse
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 noResultSet
, o que pode levar a exceções e comportamentos inesperados.Código com Problema
Classe
FerramentaDAO
pegaMaiorID
:carregaFerramenta
:Classe
AmigoDAO
pegaMaiorID
:carregaAmigo
:Problemas
Solução Proposta
A solução envolve adicionar uma verificação antes de acessar os dados do
ResultSet
. Deve-se verificar se há uma linha disponível utilizandoif (res.next())
.Correção na Classe
FerramentaDAO
pegaMaiorID
:carregaFerramenta
:Correção na Classe
AmigoDAO
pegaMaiorID
:carregaAmigo
: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