Error: "Cannot make a Static Reference to the non-static method from *"

Asked

Viewed 2,948 times

2

Good morning,

I have a following error warning. on line 23 and 24 of the User.class.

Says: Cannot make a Static Reference to the non-static method from User.

    public class UsuarioDAO {

    public static Boolean doLogin(UsuarioDAO usuario) {

        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select * from usuario where nome=? and senha=?";

        try {

            // Validar
            ps = ConectarDB.getConexao().prepareStatement(sql);
            //UsuarioModel usuario = new UsuarioModel();
            ps.setString(1, UsuarioModel.getNome());
            ps.setString(2, usuarioModel.getSenha());
            rs=ps.executeQuery();

            // Validar
            if(rs.next()) {
                return true;
            } else {
                return false;
            }            

        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }

    }

}

    public class UsuarioModel {

// Variáveis
    public String nome;
    public String senha;

// Getters & Setters
    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;
    }

    public UsuarioModel(String nome, String senha) {
        this.nome = nome;
        this.senha = senha;
    }

}

2 answers

5


On the line ps.setString(1, UsuarioModel.getNome()); change to:

ps.setString(1, usuarioModel.getNome());

Note that when calling UsuarioModel.getNome(), the U is capitalized, so Java will try to access the static method getNome() instead of instance method, which is what you probably want. That’s exactly what the error message is saying.

2

Occurs the following :

ps.setString(1, UsuarioModel.getNome()); 

This method is not static:

I believe what you wanted to do is save one UsuarioModel , correct?

Then you must pass it in the parameter!

Would look like this:

 public static Boolean doLogin(UsuarioModel usuarioModel) {

        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select * from usuario where nome=? and senha=?";

        try {

            // Validar
            ps = ConectarDB.getConexao().prepareStatement(sql);

            ps.setString(1, usuarioModel.getNome());
            ps.setString(2, usuarioModel.getSenha());
            rs=ps.executeQuery();

            // Validar
            if(rs.next()) {
                return true;
            } else {
                return false;
            }            

        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }

    }

I hope I’ve helped!

Greetings

Browser other questions tagged

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