0
I’m trying to perform a database search through java.
I am using this code, but this entering the exception:
public ArrayList<Pessoas> pesquisar(String nome) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
try(Connection con = new MySql().conecta()) {
String sql = "select *"+
" from pessoas"+
"where nome like '%?%'";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, nome);
java.sql.ResultSet rs = stmt.executeQuery(sql);
while (rs.next()){
Pessoas pesquisa = new Pessoas();
pesquisa.setNome(rs.getString("nome"));
pesquisa.setDataNasc(rs.getString("dataNasc"));
pesquisa.setTipo(TIPO.valueOf(rs.getString("sexo")));
pesquisa.setEmail(rs.getString("email"));
pesquisa.setCelular(rs.getString("celular"));
pesquisa.setTelefone(rs.getString("telefone"));
pesquisa.setEndereco(rs.getString("endereco"));
pesquisa.setNumCasa(rs.getString("numCasa"));
pesquisa.setBairro(rs.getString("bairro"));
pesquisa.setCidade(rs.getString("cidade"));
pesquisa.setCep(rs.getString("cep"));
pesquisa.setEstado(rs.getString("estado"));
pesquisa.setObservacao(rs.getString("observacao"));
// adicionando o objeto à lista
lista.add(pesquisa);
}
rs.close();
stmt.execute();
stmt.close();
} catch(SQLException e) {
System.out.println("teste15");
}
return lista;
}
That one
System.out.println("teste15");
does not serve for nothing in this code, does not help to understand why fell in the catch. So, remove this, and exchange fore.printStackTrace();
which is what will really show the reason.– user28595
So take out the
try-catch
to see the exception happen. I often say that my code rarely exceeds half a dozentry-catch
, i don’t understand why people fill it up in code, catch exception almost always leaves code less robust and no more.– Maniero
@Maniero the exception is checked, and the damn Ides indicate this solution to "solve the problem" of the checked exception. With a good intention, the IDE ends up inducing those who are learning to do something without having any idea what they are doing.
– user28595
Anyway, if you were a little more careful and put a space after the table name or a space before the
where
you would not have generated error while preparing query– Jefferson Quesado