Ir ao conteúdo
  • Cadastre-se

Java Comparar dados do MySql no Netebeans


Josues

Posts recomendados

Olá, bom dia! Seguinte, estou tentando desenvolver uma aplicação de login, mas encontrei alguns problemas na hora de comparar os dados do meu BD. Nesta aplicação eu quero que o programa compare o valor digitado no JTextLogin e quando clicar no botão ENTRAR ele me retorne com o nome da pessoa referente ao login digitado em outro frame. Segue o código abaixo:

Essa é meu acesso ao BD:

public class AcessoMySql {
    
    Connection con;
    
    public Connection conectar(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost/teste","root","");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            System.out.println("Não foi possivel encontrar o Driver!");
        } catch (SQLException ex){
            ex.printStackTrace();
            System.out.println("Não foi possivel conectar ao banco!");
        }
        return con;
    }

Esse é o meu Bean Pessoa:

 

public class Pessoa {
    
    Integer idPessoa;
    String nome;
    String login;
    String senha;
   
    public int getIdPessoa() {
        return idPessoa;
    }
    
    public void setIdPessoa(int idPessoa) {
        this.idPessoa = idPessoa;
    }
   
    public String getNome() {
        return nome;
    }

    
    public void setNome(String nome) {
        this.nome = nome;
    }
    
    public String getLogin() {
        return login;
    }
  
    public void setLogin(String login) {
        this.login = login;
    }
    
    public String getSenha() {
        return senha;
    }
   
    public void setSenha(String senha) {
        this.senha = senha;
    }
}

Esse é o meu PessoaDao:

public class PessoaDao {
   
    PreparedStatement pstm;
    ResultSet rs;   
   
    String insereDadosP = "INSERT INTO PESSOA (NOME, LOGIN, SENHA) VALUES (?,?,?)";
    String consultaP = "SELECT * FROM PESSOA WHERE LOGIN = ?";   
    
    AcessoMySql bd = new AcessoMySql();

public boolean listarPessoaNome(String login){
         boolean lis = false;
        //Pessoa pes = new Pessoa();
        try {
            pstm = bd.conectar().prepareStatement(consultaP);
            pstm.setString(1, login);
            rs = pstm.executeQuery();
         
            if(rs.next()){
                lis = true;         
                       
            }
        } catch (Exception e) {
            e.printStackTrace();
        
        } 
        return lis;
    } 
       
    public List<Pessoa> procuraNome(){
        String pN = "SELECT * FROM PESSOA";       
        PreparedStatement stm1;
        ResultSet rs1;
        
        List<Pessoa> pe = new ArrayList<>();
                
        try {
            stm1 = bd.conectar().prepareStatement(pN);
            //stm1 = bd.conectar().prepareStatement(pN);
            rs1 = stm1.executeQuery();
                    
            while(rs1.next()){
                Pessoa pess = new Pessoa();
                pess.setNome(rs1.getString("nome"));
               
                
                pe.add(pess);
            }
            
        } catch (Exception e) {
            System.out.println("Erro!" + e);
            JOptionPane.showMessageDialog(null, e);
        } finally{
            bd.desconctar();
    }
        return pe;
}

Essa é minha tela de login:

public class testeS extends javax.swing.JDialog {

    /**
     * Creates new form testeS
     */
    public testeS(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jBRetornaNome = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTLogin = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jBRetornaNome.setText("Envia Nome do BD");
        jBRetornaNome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBRetornaNomeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(75, 75, 75)
                        .addComponent(jBRetornaNome, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(112, 112, 112)
                        .addComponent(jTLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(111, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(51, 51, 51)
                .addComponent(jBRetornaNome, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(51, 51, 51)
                .addComponent(jTLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(54, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jBRetornaNomeActionPerformed(java.awt.event.ActionEvent evt) {                                              
        comparaLoBD();
        //retornaNome();
    }                                             

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(testeS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(testeS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(testeS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(testeS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                testeS dialog = new testeS(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jBRetornaNome;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTLogin;
    // End of variables declaration                   

    private Pessoa pessoa;
    private Controle controle;
    private testeP p1;
    
  
    public void comparaLoBD(){
            PessoaDao pd = new PessoaDao();
            testeP a = new testeP();
            
            for(Pessoa p: pd.procuraNome()){  
            if(pd.listarPessoaNome(jTLogin.getText())){
            
      
         dispose();
             
        a.retJlabel(p.getNome());
       a.setVisible(true);       
        
       
    }else{
                JOptionPane.showMessageDialog(null, "Erro ao comparar os valores!");
            }
  
        } 
    }
}

Essa é a tela que vai ser exibida quando houver a comparação do BD com as informações digitada pelo usuário:

public class testeP extends javax.swing.JFrame {

    /**
     * Creates new form testeP
     */
    public testeP() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLRecebeNomeBD = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLRecebeNomeBD.setFont(new java.awt.Font("Meiryo", 1, 24)); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jLRecebeNomeBD, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(41, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addComponent(jLRecebeNomeBD, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(174, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(testeP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(testeP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(testeP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(testeP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new testeP().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLRecebeNomeBD;
    // End of variables declaration                   

    public void retJlabel(String nome){
        PessoaDao pd = new PessoaDao();  
              
        jLRecebeNomeBD.setText(nome); 
         jLRecebeNomeBD.setVisible(true);
        //}
    }
}

 

Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...