Problem with a method

Asked

Viewed 45 times

0

good i have a method on the button to call my validation:

 public void valida2(){
 String Login = jLogin.getText(), Senha=jSenha.getText();
 Usuario u = new Usuario(Login,Senha);
 UsuarioDAO dao = new UsuarioDAO();
 dao.validarSenha(u);
 }

I have a question as to how to proceed with this method:

    public Usuario validarSenha(Usuario u){
     String sql = "SELECT id_usuario, login FROM usuario where login = ? and senha = ?";
     try {
         PreparedStatement stmt = con.prepareStatement(sql);
         ResultSet rs = stmt.executeQuery();
         stmt.setString(1, u.getLogin());
         stmt.setString(2, u.getSenha());

         if (rs.next()){
             Usuario usuarioLogado = new Usuario(rs.getLong("id_usuario"));
             usuarioLogado.setNome(rs.getString("nome")); // vai exibir mesmo o login?
             System.out.println("xd");
             return usuarioLogado;
         }else{
             System.out.println("xdx");
         }
         stmt.close();
         rs.close();
         con.close();  
     } catch (SQLException ex) {
         System.out.println("xdf");
         return null;
     }

     return null;
     }

when debugging he comes to that part:

ResultSet rs = stmt.executeQuery();

and then goes to the

catch (SQLException ex) {
         System.out.println("xdf");
         return null;
     }

Can you help me?

user class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Model;

/**
 *
 * @author SpiriT
 */
public class Usuario {
    private static Usuario instance;
    private Long id;
    private String login;
    private String senha;
    private String nome;


    public Usuario(String login,String senha) {
        this.login = login;
        this.senha = senha;
    }

    public Usuario(Long id) {
        this.id = id;
    }

    // construtores
    public Usuario(){}


   //sets/gets 

    public String getNome() {
        return nome;
    }

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

   public void setId(Long id){
        this.id=id;
    }
    public Long getId(){
        return id;
    }
    public void setLogin(String login){
        this.login=login;
    }
    public String getLogin(){
        return login;
    }
    public void setSenha(String senha){
        this.senha=senha;
    }
    public String getSenha(){
        return senha;
    }

    public static Usuario getInstance() {
        if (instance == null){
            instance = new Usuario();
            }
        return instance;
    }

    public void setString(int i, String login) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

user class

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package DAO;

    import Conexao.ConnectionFactory;
    import Model.Usuario;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;


    public class UsuarioDAO  {
        private Connection con;

        public UsuarioDAO(){
        this.con = new ConnectionFactory().getConnection();
        }

        public Usuario validarSenha(Usuario u){
        String sql = "SELECT id_usuario, login FROM usuario where login = ? and senha = ?";
        try {
            PreparedStatement stmt = con.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            stmt.setString(1, u.getLogin());
            stmt.setString(2, u.getSenha());
            if (rs.next()){
                Usuario usuarioLogado = new Usuario(rs.getLong("id_usuario"));
                usuarioLogado.setNome(rs.getString("nome")); // vai exibir mesmo o login?
                System.out.println("xd");
                return usuarioLogado;
            }
            stmt.close();
            rs.close();
            con.close();  
        } catch (SQLException ex) {
            Logger.getLogger(UsuarioDAO.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        return null;
        }

    }

connection class:

public class ConnectionFactory {
        public Statement statement;
        public ResultSet resultset;

        public Connection getConnection() {
        String url = "jdbc:mysql://localhost:3306/helpSemeq"+"?verifyServerCertificate=false&useSSL=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=America/Sao_Paulo"; 
        String usuario = "root";  
        String senha = ""; 
        Connection result = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            result = DriverManager.getConnection(url, usuario, senha);
            return result;                        
        }  
        catch(Exception e){  
            JOptionPane.showMessageDialog(null, e, "ERRO", JOptionPane.ERROR_MESSAGE);  
        }
        return result;
    }


    public void executeSQL(String sql) {
        try {
            statement = getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            resultset = statement.executeQuery(sql);
        } catch (SQLException sqlex) {
            System.out.println("Não foi possivel executar o comando: \n" + sqlex + "\n o sql passado foi: \n" + sql);
        }
    }
}

and the controller:

@FXML
private TextField jLogin;
@FXML
private PasswordField jSenha;

@FXML
private void handleButtonAction(ActionEvent event) {

}
@FXML
private void validar(ActionEvent event) {
    valida2();
}

public void valida2(){
String Login = jLogin.getText(), Senha=jSenha.getText();
Usuario u = new Usuario(Login,Senha);
UsuarioDAO dao = new UsuarioDAO();
dao.validarSenha(u);
}
public void validaLogin(){
    UsuarioDAO dao = new UsuarioDAO();
    List<Usuario> usuarios = dao.getList();

    for(int x = 0; x< usuarios.size(); x++){
        if(jLogin.getText().equals(usuarios.get(x).getLogin()) && jSenha.getText().equals(usuarios.get(x).getSenha())){
            Principal pr = new Principal ();
            x = usuarios.size();
            fecha();
            try {
                Usuario login = Usuario.getInstance();
                pr.start(new Stage());
            } catch (Exception ex) {
                Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else{
            if(x == usuarios.size()-1){
                Alert al = new Alert(Alert.AlertType.ERROR);
                al.setHeaderText("Login Invalido");
                al.show();
            }
        }
    }
}
  • Post the stacktrace of Exception

  • java.sql.Sqlexception: No value specified for Parameter 1

  • sorry had forgotten.

  • The first parameter (login) was not filled in, you debugged to see if it came filled in your jLogin.getText()?

  • I just checked debugging, it adds what I put on jtextfield in this part: User u = new User(Login,Password); goes to constructor and received .

  • from what I’ve seen is normal

  • I’ll edit the topic with the full code, could you check it out?

  • yes post a verifiable example, if possible put your code on Github

  • @nullptr edited the post, I have little experience with github :(, but I put all the classes I used

  • i don’t know if this method is 100% right I wanted to do it and create a global variable to save the user id on all screens.

  • @nullptr the problem was Resultset rs = stmt.executeQuery(); it was supposed to be right after set.

  • but if you can help me in this case to create a global variable to receive the value

Show 7 more comments

1 answer

0

try this:

 public Usuario validarSenha(Usuario u){
     String sql = "SELECT id_usuario, login FROM usuario where login = ? and senha = ?";
     try {
         PreparedStatement stmt = con.prepareStatement(sql);

         stmt.setString(1, u.getLogin());
         stmt.setString(2, u.getSenha());
         ResultSet rs = stmt.executeQuery();

Voce must first fill in all Statement information and then query.

Browser other questions tagged

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