Rewrite code using the Try-with-Resources resource

Asked

Viewed 95 times

0

My problem is to rewrite a code using the Try-with-Resources feature, as I’m new in the world of programming I’m not being able to learn how to do this, which is becoming something exciting, because apparently it’s simple, but I’m not getting it.

I have a validation code (it’s a simple login) but every time I log in the connection to the database remained open and could not do any other operation, Insert, update, drop, etc. Soon I was presented with the Try-with-Resources, and I need this code passed with this resource.

I’m remaking that question right with this Try-with-Resources tutorial I’m still not getting it. I hope you understand that I’m extremely new to programming.

Direct Jframe login code (which is something wrong, I know):

Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pst = null;

    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);
        }
}

So I tried to pass this same code to a class already trying to use the resource Try-with-Resources, but I could barely finish because I could not understand anything else, rs:

public class LoginDAO {

    private static final String SQL_CONSULTA = 
            "SELECT * FROM usuarios WHERE nome_usuario = ? AND senha_usuario = ?";

    public void search(Login l){

    try
    {
       Connection conn = JavaConnect.connectDb();
       PreparedStatement pstmt = conn.prepareStatement(SQL_CONSULTA);
       ){

       pstmt = setString(1, l.getNome());
       pstmt = setString(2, l.getSenha());

       pstmt.executeQuery();
    }
    }
    catch(SQLException ex)
    {
        JOptionPane.showMessageDialog(null,"Erro ao inserir dados no DataBase.");
    }
    finally
    {
        JavaConnect.DesconnectDb(l,pstmt);
    }
    }

But this code has errors as:

  • setString is not correct, it returns error telling me to create the method.
  • Desconnectdb all red.

Following, as I was unable to call the Textbox from Jframe to the class I created a GET/SET (I don’t know if this was the right way), to call them:

public class Login {

    private int id;
    private String nome;
    private String senha;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    } 
}

So to pass the Textbox values I went to Jframe and write the following code:

 private void jbtnConfimarActionPerformed(java.awt.event.ActionEvent evt) {                                             
       Login l = new  Login();
       LoginDAO dao = new LoginDAO();

       l.setNome(jtxtUsuario.getText());
       l.setSenha(jtxtSenha.getText());

       dao.search(l);

       this.dispose();
       jfrmPrincipal principal = new jfrmPrincipal();
       principal.setVisible(true);
    }  

Staff I ask patience of you but honestly I can no longer understand this, it seemed simple to write the code taking the learning of a video from the internet but understand it and trying to dissertate for myself is more complicated than I was imagining.

  • Hello, I’m remaking this question because, even with that other answer I’m still having trouble passing this code.

  • Errors are related in the way you wrote the code, try as follows: http://pastebin.com/3Lv9x6yt

  • @Denisrudneidesouza no Finally pstmt returns with error " cannot find Symbol" can explain to me why ?

  • 1

    Sorry for my lack of attention, pstmt does not exist in Finally, it was automatically closed by Try-with-Resources, in this case Javaconnect.Desconnectdb(l,pstmt); it is unnecessary

  • 1

    @Denisrudneidesouza I appreciate your time, the code you rewrote worked perfectly, it helped me identify where were my placement errors, thank you!

  • 1

    @Denisrudneidesouza Post that as an answer.

Show 1 more comment

1 answer

4


The problem lies in:

pstmt = setString(1, l.getNome());
pstmt = setString(2, l.getSenha());

Where you assign the return method setString to pstmt, the correct would be:

pstmt.setString(1, l.getNome());
pstmt.setString(2, l.getSenha());

Where to access the setString method of your Preparedstatement to define the values for the query.

Finally with bank closure is unnecessary as the connection will be automatically closed with Try-with-Resources.

The final code would look like this:

public class LoginDAO {

    private static final String SQL_CONSULTA = "SELECT * FROM usuarios WHERE nome_usuario = ? AND senha_usuario = ?";

    public void search(Login l) {

        try (Connection conn = JavaConnect.connectDb(); PreparedStatement pstmt = conn.prepareStatement(SQL_CONSULTA);) {
            pstmt.setString(1, l.getNome());
            pstmt.setString(2, l.getSenha());
            pstmt.executeQuery();
        } catch (SQLException ex){
            JOptionPane.showMessageDialog(null, "Erro ao inserir dados no DataBase.");
        }
    }
}

Browser other questions tagged

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