Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

  • 0
Josues

Como comparar dados do Mysql

Pergunta

Olá, boa tarde! Seguinte, estou tentando desenvolver uma aplicação de login, mas encontrei alguns problemas nas 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.

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;
    }
    
    public void desconctar(){
        try{
            con.close();
        }catch (SQLException ex){
            ex.printStackTrace();
        }
    }
}

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 {
   
    Statement stm;
    PreparedStatement pstm;
    ResultSet rs;
    
    String insereDados = "INSERT INTO PESSOA (codigo) VALUES (null)";
    String insereDadosP = "INSERT INTO PESSOA (NOME, LOGIN, SENHA) VALUES (?,?,?)";
    String consultaP = "SELECT * FROM PESSOA WHERE LOGIN = ?";
    //String consultaUltimo = "SELECT MAX(IDPESSOA) AS IDPESSOA FROM PESSOA";
    
    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 String retornaUltimoCodigo() {
       
       
        try {
            stm = bd.conectar().createStatement();
            rs = stm.executeQuery(consultaP);
            //rs.first();
            return rs.getString("nome");
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bd.desconctar();
        }     
        return "";
    }
    
    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();
            //rs1.first();
             //Pessoa pess = new Pessoa();
             //if(pess.getLogin().equals(rs1.getString("login"))){
           
            while(rs1.next()){
                Pessoa pess = new Pessoa();
                pess.setNome(rs1.getString("nome"));
                //pess.setLogin(rs.getString("login"));
                
                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 usuario

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

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

0 respostas a esta questão

Recommended Posts

Até agora não há respostas para essa pergunta


  • Conteúdo Similar

    • Por violin101
      Caros amigos, saudações.
       
      Estou escrevendo um Sistema Java Web e quando clico no Botão Salvar, o Java acusa esse erro:

      ERROR: Cannot invoke "Object.toString()" because the return value of "java.util.Map.get(Object)" is null
       
      Já tentei de várias formas resolver esse problema, mas não estou conseguindo.

      Por favor, alguém pode me ajudar identificar a origem e resolver o problema acima ?

      Grato,
       
      Cesar
    • Por violin101
      Caros amigos, saudações.

      Estou enfrentando um problema que não consigo entender.

      Após Instalar o MySql versão 8.0.36, funciona corretamente realizando as conexões.

      O problema é:
      ---[ após reiniciar o micro, o MySql não faz as conexões.
      --[ tenta localizar este arquivo, mas não acha: my.ini
       
      Onde localizo ou configuro este arquivo na Pasta MySql ?

      Grato,
       
      Cesar
    • Por violin101
      Caros amigos, saudações.
       
      Por favor, preciso de ajuda em Relação a Instalar o Jasper Reports no Eclipse, pois a opção de Eclipse Marketplace, não encontra para instalar.
       
      Já tentei de todas as formas mas não consegui, alguém conhece alguma rotina explicando este procedimento ?
       
      Grato,
       
      Cesar
    • Por violin101
      Caros amantes da informática.
       
      Saudações.
       
      Estou usando o Eclipse Mars versão 4.5.0  e o 4.5.2, acredito que deva ter versões mais novas. 
      Sou novato em JAVA e estou encontrando alguns problema em Instalação de alguns plugins, como por exemplo:
       
      1) quando tento instalar o JBoss Tools através do Eclipse Marteplace, o Eclipse não o encontra na lista de plugins.
      2) se tento instalar através do Install New Software, abaixa alguns arquivos, mas também não instala o JBoss.
      3) se abro o site e arrasto o download para a área de trabalho do Eclipse, também não instala o JBoss.
       
      Caros amigos, existe outra alguma forma de instalar o JBoss Tools no Eclipse e como seria ?
       
      Grato,
       
      Cesar
       
       
    • Por daemon
      Tenho 3 selects assim com varias categorias...
       
              $sql = "SELECT * FROM topicos          WHERE idcategoria = $idcategoria          AND pubdate BETWEEN NOW() - INTERVAL $intervalo1_horas_ou_minutos $tipo_intervalo1_horas_mnutos AND          NOW() - $intervalo2_horas_ou_minutos ORDER BY pubdate DESC LIMIT 1"; Preciso que na minha pagina principal (index) mostre este registro por 10minutos.. passando de 10 minutos mostra o resultado do proximo select (categoria)..
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.