Ir para conteúdo

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 ILR master
      Pessoal, pergunta bem simples. Abaixo tenho o seguinte código:
       
      <script>
      function alerta()
      {
        if (window.confirm("Você realmente quer sair?")) {
          window.open("sair.html");
      }
      }
      </script>
       
      Funciona perfeitamente, só que está abrindo em outra janela e quero que abra na mesma janela.
       
      Alguém pode me ajudar?
    • Por ILR master
      Boa tarde, pessoal.
      Espero que todos estejam bem.
       
      Seguinte:
      Tenho a seguinte consulta:
       
      $usuarios= "SELECT * FROM usuarios";
      $query= mysqli_query($conexao, $usuarios) or die ("Usuário não encontrado");
      $usuario = mysqli_fetch_array($query);
       
      Quero pegar apenas o campo 'nome' da tabela 'usuarios' e colocar todos os resultados da seguinte forma:
       
      $nomes = array("Rafael", "João", "Maria", "Pedro", "Patricia", "Camila");
       
      Agradeço desde já.
      Abs
       
       
    • Por FabianoSouza
      Tenho uma function que precisa receber 02 argumentos.
      Ela funciona se eu aplicar num select qualquer. Mas se eu aplicar num select dinâmico, ocorre erro.
      Veja trecho do meu select.
      ... SET @sql = @sql +', dbo.retornaIco_ItemBloq((SELECT COUNT(*) FROM dbo.tab AS TT2 WHERE TT2.codCategTreina = CTT.id),'+@title+') AS ''resp''' ... No caso, o primeiro argumento da function dbo.retornaIco_ItemBloq é um SELECT COUNT.
      O segundo argumento é uma variável (que está devidamente declarada e definida).
       
      O erro ocorre porque ao executar (chamando EXEC(@sql) ), o SQL entende que o segundo argumento é uma coluna da consulta principal, pois existe uma vírgula antes da variável @title (que é o segundo argumento da function).
      Repito. Se eu aplicar essa function num select normal, funciona normalmente. Porém, preciso que funcione num SQL dinâmico porque é esse é o padrão que estou adotando para o sistema todo.
       
      A function dbo.retornaIco_ItemBloq faz o seguinte:
      1) Recebe o valor do COUNT e da variável @title
      2) Se o COUNT for maior que  Zero, cria uma tag HTML (uma SPAN), define sua title com o valor da variável @title e passa para uma variável
      3) Retorna o HTML que será exibido no resultado da consulta principal
      É super simples.
       
      Há outra forma de chamar a function?
    • Por mamotinho
      Olá, estou a um tempo tentando acrescentar um codigo na coluna do SQL na qual seria VARBINARY

      A Coluna atual contém o seguinte codigo binary:
      Código (01)
      0x020009004C0101434D0101465C0101485D0101499801014B8401014E8501014F86010150D00009017A0014247D0014257B0014261600090201000903F9001420FA0014229F000923F8001427DF000128730014297600142A7E00142BFB00142CA3010147E000142DE100142EA40101443900120424001405C40101457400142F770014307F0001317C001232E6000421780001332C010A522F0108533A010354380103553001085637010357A5010166A6010167  
      No codigo acima eu gostaria de acrescentar o seguinte codigo:
      Código (02)
      0xCC010120CD010121CE010122CF010123
      no caso eu quero criar uma procedure que ao executar a função ele adicione o codigo 02 no código 01. no caso o codigo ficaria desta forma:

      0x020009004C0101434D0101465C0101485D0101499801014B8401014E8501014F86010150D00009017A0014247D0014257B0014261600090201000903F9001420FA0014229F000923F8001427DF000128730014297600142A7E00142BFB00142CA3010147E000142DE100142EA40101443900120424001405C40101457400142F770014307F0001317C001232E6000421780001332C010A522F0108533A010354380103553001085637010357A5010166A6010167CC010120CD010121CE010122CF010123



      Ficarei imensamente grato se alguém conseguir me ajudar, o orientar. sou iniciante nessa areá ainda.
    • Por Jack Oliveira
      Ola pessoal boa tarde
      estou tentando fazer um texto se mover dentro do input porem nao esta dando resultado que preciso
       
      Este é o codigo 
      <script type="text/javascript"> $(document).ready(function () { var frases = [{ 'elemento': $('input[name=search_string]'), 'frases': ["O que você está procurando?", "Buscar por: Academia, Barbearia, Churrascaria, Decoração, Escola, Farmácia, Gráfica, Imobiliaria, Lanchonete, Mecânica, Odontologia, Pizzaria...", "Faça sua busca por segmentos aqui.", "São mais de 3mil empresas para serem exploradas."] }]; animaInput(frases); }); </script>  
×

Informação importante

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