Using Try-with-Resources in Java code

Asked

Viewed 46 times

1

I have a following problem, I am unable to pass a code that I currently have and that is wrong, it works but does not close the connection to bank and gives too much error, and I wanted to use it with the Try-with-Resources feature.

Follows original code without using Try-with-Resources:

private void entrar() {

       conn = JavaConnect.connectDb();
       String sql = "SELECT * FROM usuarios where nome_usuario= ? and senha_usuario= ?";
        try{
            pst = conn.prepareStatement(sql);
            pst.setString(1,jtxtUsuario.getText());
            pst.setString(2,jtxtSenha.getText());

            rs = pst.executeQuery();
            if(rs.next()){
                jfrmPrincipal principal = new jfrmPrincipal();
                principal.setVisible(true);
                this.dispose();
            }
            else{
                JOptionPane.showMessageDialog(null, "Senha ou Usuário Incorreto");
            }
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
        }          
    }

I tried to perform the same functionality from above but could not, and currently this code is in JFRAME itself because I could not put it in a class and then call the class for the query in the frame button, because I can not call the "jtxtUsuario" in the class for example, This is possible, right ? someone can show me how the right way would be ?

I’m trying to learn but it seems that I’m really not getting, rs.

To be quite frank with everyone, I learned about Try-with-Resources today thanks to the support of another user in the community, this is leaving me with difficulty to remake this code.

  • Did you have any trouble with my other answer? By the way, in this code of yours, where are you declaring conn and pst?

  • yes @Victorstafusa, when I posted my other Insert code you passed it all ready, and I was very grateful, in this case now that it is a validation I’m trying to rewrite it with the support of the link you passed me the solution Try-with-Resources, however login is a validation and I’m not able to do it the right way, the Conn and pst are declared a little higher above, just getting out of the post, are declared as null

  • @Victorstafusa I’ll try until later, if I don’t I’ll ask another question in my community.

  • Leo, I just upgraded that other answer of mine, I believe you’ve read, to elucidate this problem. I thought I had covered everything I needed there, but you found a point I forgot to mention. Thank you very much.

No answers

Browser other questions tagged

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