Verificar se cadastro já existe no banco de dados

35 respostas Resolvido
L

Bom dia senhores,

Venho por meio deste tópico com uma dúvida. Já tentei de todas as formas, só que nada dá certo.

Bom, este é meu código de cadastro.

Usuario Usuario = new Usuario();

Usuario.setNome(camponome.getText());

Usuario.setCpf(campocpf.getText());

Usuario.setEndereco(campoend.getText());

Usuario.setTel1(campotel1.getText());

Usuario.setTel2(campotel2.getText());

Usuario.setEmail(campoemail.getText());

Usuario.setPerfil((String) campoperf.getSelectedItem());

Usuario.setUsuario(campousu.getText());

Usuario.setSenha(camposenha.getText());
if ((camponome.getText().isEmpty()) || (campoend.getText().isEmpty()) || (campocpf.getText().isEmpty()) || (campotel1.getText().isEmpty()) || (campoemail.getText().isEmpty())|| (campousu.getText().isEmpty())|| (camposenha.getText().isEmpty())|| (campoconfsenha.getText().isEmpty())) {
        JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios!", "Atenção", JOptionPane.WARNING_MESSAGE);
    } else {
        
        if (new String(camposenha.getPassword()).equals(new String(campoconfsenha.getPassword()))) {
            UsuarioDAO DAO = new UsuarioDAO();
            DAO.cadastrarusuario(Usuario);
            JOptionPane.showMessageDialog(null, "Usuário " + camponome.getText() + " cadastrado com sucesso!");
            camponome.setText(null);
            campocpf.setText(null);
            campoend.setText(null);
            campotel1.setText(null);
            campotel2.setText(null);
            campoemail.setText(null);
            campousu.setText(null);
            camposenha.setText(null);
            campoconfsenha.setText(null);

        } else {
            JOptionPane.showMessageDialog(null, "Senhas não conferem!", "Atenção", JOptionPane.WARNING_MESSAGE);
        }
    }

O que eu desejo pode ser muito simples para vocês, porém não estou conseguindo de nenhuma forma, já pesquisei bastante, to a mais de 2 dias pesquisando e resolvi pedir recursos a vocês, não precisa me dar de mãos beijadas, só me dando uma luz eu já agradeço.

Bom, vamos lá, o que eu quero é muito simples, eu quero que o sistema busque no banco de dados se já há o cpf que estão cadastrando no momento.

35 Respostas

Jonathan_Medeiros

Pega o CPF digitado pelo usuário, faz uma consulta na sua tabela de cadastro pelo número do CPF, se a consulta retornar 1 registro, significa que já existe um cadastro com o CPF em questão, caso contrário, segue o fluxo normal do cadastro.

L

poderia dar um exemplo?

Jonathan_Medeiros

Monte um select de consulta mais ou menos igual o exemplo abaixo.

SELECT COUNT(*) AS REGISTRO FROM TABELA_CADASTRO WHERE CPF LIKE '[telefone removido]'

Depois que executar recupere o retorno do resultset e veja se o retorno foi 0 ou 1, se for 0 é porque não existe registro cadastrado, se retornar 1 é porque existe o registro cadastrado.

L

nada feito mano, poderia me dar um exemplo mais específico? desculpe o incomodo

Jonathan_Medeiros

Mais específico que isso só se eu te der o exemplo pronto, o que não farei, por gentileza seja mais pontual com o que você tem dúvida, qual ponto não está claro pra você, poste o seu código mostrando como você tentou fazer, que desta forma eu consigo te ajudar de uma maneira mais assertiva.

L
código completo ficou assim:


    Usuario Usuario = new Usuario();
    Usuario.setNome(camponome.getText());
    Usuario.setCpf(campocpf.getText());
    Usuario.setEndereco(campoend.getText());
    Usuario.setTel1(campotel1.getText());
    Usuario.setTel2(campotel2.getText());
    Usuario.setEmail(campoemail.getText());
    Usuario.setPerfil((String) campoperf.getSelectedItem());
    Usuario.setUsuario(campousu.getText());
    Usuario.setSenha(camposenha.getText());

    if ((camponome.getText().isEmpty()) || (campoend.getText().isEmpty()) || (campocpf.getText().isEmpty()) || (campotel1.getText().isEmpty()) || (campoemail.getText().isEmpty())|| (campousu.getText().isEmpty())|| (camposenha.getText().isEmpty())|| (campoconfsenha.getText().isEmpty())) {
        JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios!", "Atenção", JOptionPane.WARNING_MESSAGE);
    } else {
        try {
            String sql = "Select * FROM usuarios where cpf like '0000000'";
            if(rs.next()){
                String cpf = rs.getString(campocpf.getText());
                if(cpf.equals(1)){
                    JOptionPane.showMessageDialog(null,"CPF já está cadastrado.");
                }else{
                     if (new String(camposenha.getPassword()).equals(new String(campoconfsenha.getPassword()))) {
            UsuarioDAO DAO = new UsuarioDAO();
            DAO.cadastrarusuario(Usuario);
            JOptionPane.showMessageDialog(null, "Usuário " + camponome.getText() + " cadastrado com sucesso!");
            camponome.setText(null);
            campocpf.setText(null);
            campoend.setText(null);
            campotel1.setText(null);
            campotel2.setText(null);
            campoemail.setText(null);
            campousu.setText(null);
            camposenha.setText(null);
            campoconfsenha.setText(null);

        } else {
            JOptionPane.showMessageDialog(null, "Senhas não conferem!", "Atenção", JOptionPane.WARNING_MESSAGE);
        }
                }
            }
            
            
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
       
    }

OBS: sou novato no ramo.

L

Foi o que eu pedi acima " não precisa me dar de mãos beijadas". Eu só quero uma luz.

Jonathan_Medeiros

Veja bem, tu cria a String com o SQL da consulta com o valor de comparação fixo, o valor de comparação tem que ser o texto digitado no seu campo de CPF, depois você tenta comparar o resultset, mas em nenhum momento você faz a execução da consulta, logo seu resultset estará nulo.

Obs: Utilize sempre rs.first() para consultas que devem retornar registros únicos, como é o seu caso, utilize somente rs.next() para manipular uma lista de resultados!

L

de que forma poderia me ajudar?

Jonathan_Medeiros

Ajudar de que forma você se refere?

A ajuda que te dei foi dizer exatamente o que você tem de fazer para seu código funcionar, se tudo o que eu te disse não está fazendo nenhum sentido pra ti, então você está pondo a carroça na frente dos bois, se for esse o caso, te recomendo parar de trabalhar com interface gráfica, e estudar primeiro todos os conceitos básicos da programação em java, para depois sim começar a trabalhar com interface gráfica.

L

:disappointed_relieved: nossa

L

tudo bem. Ninguém nasce sabendo, só pedi uma ajuda

Jonathan_Medeiros

Sim amigo, e foi justamente o que fiz, te orientei sobre o que você tem que fazer, agora se mesmo assim você continua perdido concorda comigo que te falta alguns conceitos ?

Ou se caso algo que eu tenha dito não ficou muito compreensivo pra ti, me diga, que desta forma eu tento reformular de uma maneira mais simples.

A intenção é ajudar, mas pra isso você tem que se ajudar também.

L

Bom, tá certo. Tentei de uma outra forma.

Usuario Usuario = new Usuario();
    Usuario.setNome(camponome.getText());
    Usuario.setCpf(campocpf.getText());
    Usuario.setEndereco(campoend.getText());
    Usuario.setTel1(campotel1.getText());
    Usuario.setTel2(campotel2.getText());
    Usuario.setEmail(campoemail.getText());
    Usuario.setPerfil((String) campoperf.getSelectedItem());
    Usuario.setUsuario(campousu.getText());
    Usuario.setSenha(camposenha.getText());

    if ((camponome.getText().isEmpty()) || (campoend.getText().isEmpty()) || (campocpf.getText().isEmpty()) || (campotel1.getText().isEmpty()) || (campoemail.getText().isEmpty())|| (campousu.getText().isEmpty())|| (camposenha.getText().isEmpty())|| (campoconfsenha.getText().isEmpty())) {
        JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios!", "Atenção", JOptionPane.WARNING_MESSAGE);
    } else {
        try {
            String sql = "Select * FROM usuarios where cpf like '[telefone removido]'";
            if(rs.first()){
                String cpf = rs.getString(2);
                if(cpf.equals(campocpf.getText())){
                    JOptionPane.showMessageDialog(null,"CPF já está cadastrado.");
                }else{
                     if (new String(camposenha.getPassword()).equals(new String(campoconfsenha.getPassword()))) {
            UsuarioDAO DAO = new UsuarioDAO();
            DAO.cadastrarusuario(Usuario);
            JOptionPane.showMessageDialog(null, "Usuário " + camponome.getText() + " cadastrado com sucesso!");
            camponome.setText(null);
            campocpf.setText(null);
            campoend.setText(null);
            campotel1.setText(null);
            campotel2.setText(null);
            campoemail.setText(null);
            campousu.setText(null);
            camposenha.setText(null);
            campoconfsenha.setText(null);

        } else {
            JOptionPane.showMessageDialog(null, "Senhas não conferem!", "Atenção", JOptionPane.WARNING_MESSAGE);
        }
                }
            }
            
            
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
       
    }

Só que eu não sei se cometi um erro de iniciante, mas tá dando java,langnullpointerexception, eu gostaria que me esclarecesse onde está o erro no código.

Jonathan_Medeiros

Você só inverteu a ordem do código, mas continua como antes, sua string SQL está com o campo de comparação fixo com ‘[telefone removido]’ ao invés do número digitado no seu campo CPF.
Você também não faz a execução do SQL para obter o retorno, você só criou a String.

L

entao no lugar do 0000 seria +campocpf.getText();?

Jonathan_Medeiros

Aqui tem um tutorial bem bacana que ensina como fazer a manipulação dos dados.

Jonathan_Medeiros

Exatamente, pois o que queremos é comparar o valor digitado no campo CPF não é ?

L

muito obrigado, era desse tipo de luz q eu tava falando kkkk, mas ai resolveria o java.lang.blablabla?

Jonathan_Medeiros
Solucao aceita

Não, pois o NullPointerException é disparado sempre que tentamos utilizar um objeto nulo, no seu caso acredito que seja o resultset.
Mas para desencargo de consciência, faz debug da sua aplicação e acompanha passo a passo que você vai conseguir visualizar pontos que estão errados de maneira bem fácil.

L
Usuario Usuario = new Usuario();

Usuario.setNome(camponome.getText());

Usuario.setCpf(campocpf.getText());

Usuario.setEndereco(campoend.getText());

Usuario.setTel1(campotel1.getText());

Usuario.setTel2(campotel2.getText());

Usuario.setEmail(campoemail.getText());

Usuario.setPerfil((String) campoperf.getSelectedItem());

Usuario.setUsuario(campousu.getText());

Usuario.setSenha(camposenha.getText());
if ((camponome.getText().isEmpty()) || (campoend.getText().isEmpty()) || (campocpf.getText().isEmpty()) || (campotel1.getText().isEmpty()) || (campoemail.getText().isEmpty()) || (campousu.getText().isEmpty()) || (camposenha.getText().isEmpty()) || (campoconfsenha.getText().isEmpty())) {
        JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios!", "Atenção", JOptionPane.WARNING_MESSAGE);
    } else {
                        String sql = "Select * FROM usuarios where cpf like "+campocpf.getText();
        try {
pst=conexao.prepareStatement(sql);

pst.setString(2,campocpf.getText());

rs=pst.executeQuery();

if (rs.first()) {

if (rs.equals(sql)) {

JOptionPane.showMessageDialog(null, CPF  está cadastrado.);

} else {

if (new String(camposenha.getPassword()).equals(new String(campoconfsenha.getPassword()))) {

UsuarioDAO DAO = new UsuarioDAO();

DAO.cadastrarusuario(Usuario);

JOptionPane.showMessageDialog(null, Usuário " + camponome.getText() + " cadastrado com sucesso!);

camponome.setText(null);

campocpf.setText(null);

campoend.setText(null);

campotel1.setText(null);

campotel2.setText(null);

campoemail.setText(null);

campousu.setText(null);

camposenha.setText(null);

campoconfsenha.setText(null);
} else {
                        JOptionPane.showMessageDialog(null, "Senhas não conferem!", "Atenção", JOptionPane.WARNING_MESSAGE);
                    }
                }
            }

        } catch (Exception e) {
    JOptionPane.showMessageDialog(null, e);
        }

    }

Outra tentativa, permanece o java.lang…

staroski

Você não está fazendo nada com a vaiável sql.

Onde e como você inicializou a variável rs?

Em princípio é a implementação do método cadastrarusuario que deveria verificar se já existe aquele usuário na base de dados.

L

Boa noite, Luiz Henrique

Conseguiu resolver mano? Caso não, me avisa que te ajudo com mais calma.

Vlw!

L

nada foi resolvido

L

Consegui não mano, o novo código ficou assim:

Usuario Usuario = new Usuario();

Usuario.setNome(camponome.getText());

Usuario.setCpf(campocpf.getText());

Usuario.setEndereco(campoend.getText());

Usuario.setTel1(campotel1.getText());

Usuario.setTel2(campotel2.getText());

Usuario.setEmail(campoemail.getText());

Usuario.setPerfil((String) campoperf.getSelectedItem());

Usuario.setUsuario(campousu.getText());

Usuario.setSenha(camposenha.getText());
if ((camponome.getText().isEmpty()) || (campoend.getText().isEmpty()) || (campocpf.getText().isEmpty()) || (campotel1.getText().isEmpty()) || (campoemail.getText().isEmpty()) || (campousu.getText().isEmpty()) || (camposenha.getText().isEmpty()) || (campoconfsenha.getText().isEmpty())) {
        JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios!", "Atenção", JOptionPane.WARNING_MESSAGE);
    } else {
                        String sql = "SELECT * FROM USUARIOS WHERE CPF LIKE '" + campocpf.getText().trim() + "' ";
        try {
pst=conexao.prepareStatement(sql);

rs=pst.executeQuery();

if (rs.first()) {
JOptionPane.showMessageDialog(null, "CPF já está cadastrado.");
            }  else {
                    if (new String(camposenha.getPassword()).equals(new String(campoconfsenha.getPassword()))) {
                        UsuarioDAO DAO = new UsuarioDAO();
                        DAO.cadastrarusuario(Usuario);
                        JOptionPane.showMessageDialog(null, "Usuário " + camponome.getText() + " cadastrado com sucesso!");
                        camponome.setText(null);
                        campocpf.setText(null);
                        campoend.setText(null);
                        campotel1.setText(null);
                        campotel2.setText(null);
                        campoemail.setText(null);
                        campousu.setText(null);
                        camposenha.setText(null);
                        campoconfsenha.setText(null);

                    } else {
                        JOptionPane.showMessageDialog(null, "Senhas não conferem!", "Atenção", JOptionPane.WARNING_MESSAGE);
                }
            }

        } catch (Exception e) {
    JOptionPane.showMessageDialog(null, e);
        }

    }
marco_aurelioo

Bom dai Luiz, faz o seguinte:
coloca todo o metodo no post pq não da para identificar neste trecho de cod onde vc cria o ResultSet e a Conexao
descreve o erro que vc esta tomando coloca o log do erro ou a mensagem que vc tah tomando no seu editor de cod
tendo isso consigo te ajudar

L
// TENTA USAR ESSE CÓDIGO... JÁ VAI TE DÁ UMA IDEIA.
Usuario usuario = new Usuario();

usuario.setNome(camponome.getText());

usuario.setCpf(campocpf.getText());

usuario.setEndereco(campoend.getText());

usuario.setTel1(campotel1.getText());

usuario.setTel2(campotel2.getText());

usuario.setEmail(campoemail.getText());

usuario.setPerfil((String) campoperf.getSelectedItem());

usuario.setUsuario(campousu.getText());

usuario.setSenha(camposenha.getText());
if (usuario.getNome().getText().equals(" ") || usuario.getCpf().getText().equals(" ") || usuario.getEndereco().getText().equals(" ") || usuario.getTel1().getText().equals(" ") || usuario.getEmail().getText().equals(" ") || usuario.getUsuario().getText().equals(" ") || usuario.getSenha().getText().equals(" ")) {
        JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios!", "Atenção", JOptionPane.WARNING_MESSAGE);
    } else {
        try {
            pst = conexao.prepareStatement("select cpf from usuarios where cpf = ?;");
            pst.setString(usuario.getCpf().getText());
            rs = pst.executeQuery();

            if (rs.next()) {
                String cpf = rs.getString(1); // AQUI VOCÊ COLOCA O NUMERO DA COLUNA CPF NA SUA TABELA.
                if (cpf.equals(usuario.getCpf().getText())) {
                    JOptionPane.showMessageDialog(null, "O CPF JÁ ESTÁ CADASTRADO!");
                } else {
                    if (new String(camposenha.getPassword()).equals(new String(campoconfsenha.getPassword()))) {
                        UsuarioDAO DAO = new UsuarioDAO();
                        DAO.cadastrarusuario(Usuario);
                        JOptionPane.showMessageDialog(null, "Usuário " + camponome.getText() + " cadastrado com sucesso!");
                        camponome.setText(null);
                        campocpf.setText(null);
                        campoend.setText(null);
                        campotel1.setText(null);
                        campotel2.setText(null);
                        campoemail.setText(null);
                        campousu.setText(null);
                        camposenha.setText(null);
                        campoconfsenha.setText(null);
                    } else {
                        JOptionPane.showMessageDialog(null, "Senhas não conferem!", "Atenção", JOptionPane.WARNING_MESSAGE);
                    }
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }
L

Dá pra melhorar esse código.

Faz essa consulta se o CPF já esta cadastrado tudo dentro do seu método DAO.cadastrarusuario(usuario).
Depois que você verifica se os campos estão preenchidos ou não, chama só o método.

A parte de conexão tenta deixar tudo dentro da sua classe DAO.

Vlw!

L

package GUI;

import java.sql.Connection;

import ping.Usuario;

import DAO.UsuarioDAO;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import javax.swing.JOptionPane;

public class CadastroUsuarios extends javax.swing.JFrame {

Connection conexao = null;
PreparedStatement pst = null;
ResultSet rs = null;

public CadastroUsuarios() {
    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() {

    jLabel1 = new javax.swing.JLabel();
    camponome = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    campocpf = new javax.swing.JFormattedTextField();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    campoemail = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    campotel2 = new javax.swing.JFormattedTextField();
    campotel1 = new javax.swing.JFormattedTextField();
    jLabel6 = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();
    campoperf = new javax.swing.JComboBox<>();
    BtnCad = new javax.swing.JButton();
    jLabel8 = new javax.swing.JLabel();
    campousu = new javax.swing.JTextField();
    jLabel9 = new javax.swing.JLabel();
    jLabel10 = new javax.swing.JLabel();
    camposenha = new javax.swing.JPasswordField();
    campoconfsenha = new javax.swing.JPasswordField();
    campoend = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setResizable(false);
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

    jLabel1.setText("Nome:");
    getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 50, -1, -1));
    getContentPane().add(camponome, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 45, 635, -1));

    jLabel2.setText("CPF:");
    getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 100, -1, -1));

    try {
        campocpf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
    } catch (java.text.ParseException ex) {
        ex.printStackTrace();
    }
    getContentPane().add(campocpf, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 95, 130, -1));

    jLabel3.setText("Endereço:");
    getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 150, -1, -1));

    jLabel4.setText("Email:");
    getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 200, -1, -1));
    getContentPane().add(campoemail, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 195, 470, -1));

    jLabel5.setText("Telefone 1:");
    getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 100, -1, -1));

    campotel2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter()));
    campotel2.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            campotel2MouseClicked(evt);
        }
    });
    campotel2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            campotel2ActionPerformed(evt);
        }
    });
    campotel2.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            campotel2KeyPressed(evt);
        }
    });
    getContentPane().add(campotel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(505, 95, 130, -1));

    try {
        campotel1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)#####-####")));
    } catch (java.text.ParseException ex) {
        ex.printStackTrace();
    }
    getContentPane().add(campotel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(285, 95, 130, -1));

    jLabel6.setText("Telefone 2:*");
    getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 100, -1, -1));

    jLabel7.setText("Perfil:");
    getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 200, -1, -1));

    campoperf.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Administrador", "Ajudante" }));
    getContentPane().add(campoperf, new org.netbeans.lib.awtextra.AbsoluteConstraints(595, 195, 110, -1));

    BtnCad.setText("Cadastrar");
    BtnCad.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            BtnCadActionPerformed(evt);
        }
    });
    getContentPane().add(BtnCad, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 420, 120, 60));

    jLabel8.setText("Usuário:");
    getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 250, -1, -1));
    getContentPane().add(campousu, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 245, 150, -1));

    jLabel9.setText("Senha:");
    getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 300, -1, -1));

    jLabel10.setText("Confirme sua senha:");
    getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 350, -1, -1));
    getContentPane().add(camposenha, new org.netbeans.lib.awtextra.AbsoluteConstraints(73, 295, 120, -1));
    getContentPane().add(campoconfsenha, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 345, 120, -1));
    getContentPane().add(campoend, new org.netbeans.lib.awtextra.AbsoluteConstraints(85, 145, 610, -1));

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

private void BtnCadActionPerformed(java.awt.event.ActionEvent evt) {                                       

    Usuario Usuario = new Usuario();
    Usuario.setNome(camponome.getText());
    Usuario.setCpf(campocpf.getText());
    Usuario.setEndereco(campoend.getText());
    Usuario.setTel1(campotel1.getText());
    Usuario.setTel2(campotel2.getText());
    Usuario.setEmail(campoemail.getText());
    Usuario.setPerfil((String) campoperf.getSelectedItem());
    Usuario.setUsuario(campousu.getText());
    Usuario.setSenha(camposenha.getText());

    if ((camponome.getText().isEmpty()) || (campoend.getText().isEmpty()) || (campocpf.getText().isEmpty()) || (campotel1.getText().isEmpty()) || (campoemail.getText().isEmpty()) || (campousu.getText().isEmpty()) || (camposenha.getText().isEmpty()) || (campoconfsenha.getText().isEmpty())) {
        JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios!", "Atenção", JOptionPane.WARNING_MESSAGE);
    } else {
                        String sql = "SELECT * FROM USUARIOS WHERE CPF LIKE '" + campocpf.getText().trim() + "' ";
        try {
pst=conexao.prepareStatement(sql);

pst.setString(1, campocpf.getText());

rs=pst.executeQuery();

if (rs.first()) {
JOptionPane.showMessageDialog(null, "CPF já está cadastrado.");
            }  else {
                    if (new String(camposenha.getPassword()).equals(new String(campoconfsenha.getPassword()))) {
                        UsuarioDAO DAO = new UsuarioDAO();
                        DAO.cadastrarusuario(Usuario);
                        JOptionPane.showMessageDialog(null, "Usuário " + camponome.getText() + " cadastrado com sucesso!");
                        camponome.setText(null);
                        campocpf.setText(null);
                        campoend.setText(null);
                        campotel1.setText(null);
                        campotel2.setText(null);
                        campoemail.setText(null);
                        campousu.setText(null);
                        camposenha.setText(null);
                        campoconfsenha.setText(null);

                    } else {
                        JOptionPane.showMessageDialog(null, "Senhas não conferem!", "Atenção", JOptionPane.WARNING_MESSAGE);
                }
            }

        } catch (Exception e) {
    JOptionPane.showMessageDialog(null, e);
        }

    }


}                                      

private void campotel2ActionPerformed(java.awt.event.ActionEvent evt) {                                          

}                                         

private void campotel2MouseClicked(java.awt.event.MouseEvent evt) {                                       
    try {
        campotel2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)#####-####")));
    } catch (java.text.ParseException ex) {
        ex.printStackTrace();
    }
}                                      

private void campotel2KeyPressed(java.awt.event.KeyEvent evt) {                                     

}                                    

/**
 * @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(CadastroUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(CadastroUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(CadastroUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(CadastroUsuarios.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 CadastroUsuarios().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton BtnCad;
private javax.swing.JPasswordField campoconfsenha;
private javax.swing.JFormattedTextField campocpf;
private javax.swing.JTextField campoemail;
private javax.swing.JTextField campoend;
private javax.swing.JTextField camponome;
private javax.swing.JComboBox<String> campoperf;
private javax.swing.JPasswordField camposenha;
private javax.swing.JFormattedTextField campotel1;
private javax.swing.JFormattedTextField campotel2;
private javax.swing.JTextField campousu;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
// End of variables declaration

}

L

esse código está dando erro mano

staroski

Prezado, escuta seus colegas do fórum e implementa a verificação do CPF dentro do método cadastrarusuario de sua classe DAO.

E por favor, quando postar código no fórum, formata ele usando o botão </>, pois do jeito que está é muito ruim de ler e copiar.

L

Vamos lá. De fato eu errei em alguns pontos…

altere essas partes…

if (usuario.getNome().equals(" “) || usuario.getCpf().equals(” “) || usuario.getEndereco().equals(” “) || usuario.getTel1().equals(” “) || usuario.getEmail().equals(” “) || usuario.getUsuario().equals(” “) || usuario.getSenha().equals(” ")) {

JOptionPane.showMessageDialog(null, Os campos não podem retornar vazios!, Atenção, JOptionPane.WARNING_MESSAGE);

}
pst = conexao.prepareStatement(select cpf from usuarios where cpf = ?;);

pst.setString(1, usuario.getCpf());

rs = pst.executeQuery();
if(rs.next()){

String cpf = rs.getString(1);

if(cpf.equals(usuario.getCpf())){

JOptionPane.showMessageDialog(null, O CPF JÁ ESTÁ CADASTRADO!);

}

}

Verifique novamente…

L

nada ainda guerreiro

minha classe DAO é essa.

package DAO;

import java.sql.*;

import ping.Usuario;

import factory.moduloconexao;
public class UsuarioDAO {

private Connection connection;

String nome,cpf,endereco,tel1,tel2,email;

String usuario;

String senha;

String perfil;
Connection conexao = null;
PreparedStatement pst = null;
ResultSet rs = null;



public void cadastrarusuario(Usuario Usuario){
    String sql = "INSERT INTO usuarios(nome,cpf,endereco,tel1,tel2,email,perfil,usuario,senha) VALUES(?,?,?,?,?,?,?,?,?)";
    try {
                PreparedStatement stmt = connection.prepareStatement(sql);
       stmt.setString(1, Usuario.getNome());
       stmt.setString(2, Usuario.getCpf());
       stmt.setString(3, Usuario.getEndereco());
       stmt.setString(4, Usuario.getTel1());
       stmt.setString(5, Usuario.getTel2());
       stmt.setString(6, Usuario.getEmail());
       stmt.setString(7, Usuario.getPerfil());
       stmt.setString(8, Usuario.getUsuario());
       stmt.setString(9, Usuario.getSenha());
       stmt.execute();      
    } catch (SQLException u) {
        throw new RuntimeException(u);
    }
}
 

      public UsuarioDAO(){ 
 this.connection = new moduloconexao().conector();
      }

}

L

A parte que faz a verificação se o CPF está cadastrado ou não é essa

pst = conexao.prepareStatement(select cpf from usuarios where cpf = ?;”);
pst.setString(1, usuario.getCpf());
rs = pst.executeQuery();

if(rs.next()){
String cpf = rs.getString(1);
if(cpf.equals(usuario.getCpf())){
JOptionPane.showMessageDialog(null, O CPF JÁ ESTÁ CADASTRADO!);
}
}

Não tem erro.

staroski
private boolean jaExiste() {
    try {
        String sql = "SELECT cpf FROM usuarios WHERE cpf like ?";
        PreparedStatement stmt = connection.prepareStatement(sql);
        stmt.setString(1, usuario.getCpf());
        ResultSet result = stmt.executeQuery();
        return result.next();
    } catch (SQLException u) {
        throw new RuntimeException(u);
    }
    return false;
}

public void cadastrarUsuario(Usuario usuario){
    if (jaExiste(usuario)) {
        throw new UsuarioJaExisteException();
    }
    try {
        String sql = "INSERT INTO usuarios (nome, cpf, endereco, tel1, tel2, email, perfil, usuario, senha) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement stmt = connection.prepareStatement(sql);
        stmt.setString(1, usuario.getNome());
        stmt.setString(2, usuario.getCpf());
        stmt.setString(3, usuario.getEndereco());
        stmt.setString(4, usuario.getTel1());
        stmt.setString(5, usuario.getTel2());
        stmt.setString(6, usuario.getEmail());
        stmt.setString(7, usuario.getPerfil());
        stmt.setString(8, usuario.getUsuario());
        stmt.setString(9, usuario.getSenha());
        stmt.executeUpdate();
    } catch (SQLException u) {
        throw new RuntimeException(u);
    }
}
Criado 12 de dezembro de 2018
Ultima resposta 13 de dez. de 2018
Respostas 35
Participantes 5