I'm making a system with a complete CRUD, the only problem I have is that I can't retrieve 1 object from my database, I can list all the objects but not get only 1, I'm using MVC and java web.
Here I leave the servlet that executes the search
@Override
public Usuario_DTO_bean mostrarUsuario(String usu) {
Usuario_DTO_bean usuarioMostrar= new Usuario_DTO_bean(1, "falla", "falla", "falla", 1, "falla", "falla", "falla");
try {
String sql="select * from usuario where usuario =?";
con=Conector.connect();
PreparedStatement statement;
statement=con.prepareStatement(sql);
statement.setString(1,usu);
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
int id = resultSet.getInt("id");
String usuario = resultSet.getString("usuario");
String clave = resultSet.getString("clave");
String permisos=resultSet.getString("permisos");
int estado=resultSet.getInt("estado");
String nombre=resultSet.getString("nombre");
String apellido_p=resultSet.getString("apellido_p");
String apellido_m=resultSet.getString("apellido_m");
usuarioMostrar=new Usuario_DTO_bean(id, usuario, clave, permisos, estado, nombre, apellido_p,apellido_m);
}
resultSet.close();
statement.close();
con.close();
} catch (Exception e) {
// TODO: handle exception
}
return usuarioMostrar;
}
After testing, I think the problem is in this line of code
ResultSet resultSet = statement.executeQuery(sql);
Since after this line no code is executed, not even a simple println in the console and it jumps straight to the return, as if the try detected an error and exited the block.
With this code in a main I execute the function
String registro="SI-84";
Usuario_DTO_bean usuario;
Usuario_DTO_bo bo=new Usuario_DTO_bo();
usuario=bo.mostrarUsuario(registro);
System.out.println(usuario.getId());
System.out.println(usuario.getUsuario());
They must know that the user with record SI-84 exists, but instead of returning their values, it returns the following
In addition to the error of not putting an exception in the catch as they told me, the problem was that perhaps because I was using SQLite it did not let me use PrepareStatement, since the console error indicated an SQL error saying that it did not support the PrapareStatement with which I wanted to use the typical "?" to replace the data.
Now instead of using PrepareStatement , just use Statement and I made a small change in the sql statement, with this it works great :D
In the first place, those values are returned to you because you are instantiating it at the beginning
From what I see, so far the method seems fine to me. As they tell you, you have to print the exception something like this:
If there is an error, know exactly what the error is that you get in order to help you. Cheers