Rewrite code using the try-with-resources feature [duplicate]

0

My problem is to rewrite a code using the try-with-resources feature, as I'm new to the programming world, I'm not able to learn how to do this, which is becoming rather overwhelming because it's apparently simple but I'm not getting it.

I have a validation code (it is a simple login) but every time I log in the connection to the database remained open and I could not do any other operations, insert, update, drop, etc. I was introduced to the try-with-resources feature, and I need this code passed with this feature.

I'm redoing this question even with this try tutorial -with-resources I still can not figure it out. I hope you understand that I'm extremely new to programming.

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

Then I tried to pass this same code to a class already trying to use the try-with-resources feature, but I could hardly 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 like:

  • The setString is not correct, it returns me error saying to create the method.
  • DisconnectDB is all red.

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 values of the TextBox I went in the Jframe and writes 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);
    }  

I ask your patience, but I honestly can not understand it anymore, it seemed simple to write the code by learning an internet video but understanding it and trying to give it to myself is more complicated than I was imagining .

    
asked by anonymous 25.12.2016 / 16:02

1 answer

4

The problem is:

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

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

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

Where you access the setString method of your PreparedStatement to set the values for the query.

The finally closing the database is unnecessary since the connection will be closed automatically with try-with-resources.

The final code looks 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.");
        }
    }
}
    
26.12.2016 / 13:18