Search in the Database

Asked

Viewed 69 times

-1

I’m in doubt on a role of how to do a comic search. It’s going to catch. Can anyone tell why? And how to solve?

That is the function

public void consultar(){
    String sql ="select * from tbaluno where idaluno=?";
    try {
         PreparedStatement stmt = connection.prepareStatement(sql);
         stmt.setString(1, textid.getText());
         rs = stmt.executeQuery();
         if(rs.next())

         System.out.println(textid);
         if(rs.next()){
             Usuario usuario = new Usuario();
             usuario.setNomealuno(rs.getString("nomealuno"));
             txtnome.setText(rs.getString(2));  
         }else{

         }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

The message that appears when I put an existing id in the database: java.lang.NullPointerException

EDIT-> Mysql Table, Contains:

ID | Name

1 | Vinicius

I wanted when I put the id 1, to show in the field the name "Vinicius". The change I made in the function consult above, was just remove one if and exchange the other by while.

  • Do not know, because there is no way to test, all these variables inside Try may be causing the error, provide a [mcve] so that it is possible to verify the origin of the problem.

1 answer

1

Probably in your table there are more things than nomealuno one of them must be the idaluno, which comes before.

Once the program runs it goes through the only if effective (although there is one more) and cannot access the column of the name, generating a Nullpointer.

Try trading the if for one while(rs.next()) since you select all attributes in select. Or change select to just name

  • For me, that would be an answer.

  • Hi, I edited as you said, I tried to explain better. Still the same mistake.

  • I didn’t understand the editing, you tested that line: if(rs.next()){ with while(rs.next()){ ?

  • No, I tested it not like that. I put only While(rs.next()) {.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.