2
In my class SocioDAO
I have the method salvarSocio()
which will be saved in the database. In my class DadosUsuario
I have the information that needs to be recorded
in the bank in case cadastrarUsuario()
. How to proceed to validate CPF?
I didn’t want to put validation into my method cadastrarUsuario()
because not the same shouldn’t get too big.
public class SocioDAO {
public void salvarSocio(Socio socio) throws SQLException {
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO socio ");
sql.append("(nome, telefone, ddd, email, cpf) ");
sql.append("VALUES (?, ?, ?, ?, ?) ");
Connection conexao = ConexaoFactory.conectar();
PreparedStatement comando = conexao.prepareStatement(sql.toString());
comando.setString(1, socio.getNome());
comando.setInt(2, socio.getTelefone());
comando.setInt(3, socio.getDdd());
comando.setString(4, socio.getEmail());
comando.setString(5, socio.getCpf());
comando.executeUpdate();
}
public class DadosUsuario {
static Scanner scan = new Scanner(System.in);
public void cadastrarUsuario() {
Socio cadastrarUser = new Socio();
System.out.println("Informe um nome: ");
cadastrarUser.setNome(scan.nextLine());
System.out.println("Informe um telefone: ");
cadastrarUser.setTelefone(scan.nextInt());
System.out.println("Informe o DDD: ");
cadastrarUser.setDdd(scan.nextInt());
System.out.println("Informe o email: ");
cadastrarUser.setEmail(scan.next());
System.out.println("Informe o cpf: ");
cadastrarUser.setCpf(scan.next());
SocioDAO dao = new SocioDAO();
try {
dao.salvarSocio(cadastrarUser);
System.out.println("USUÁRIO CADASTRADO COM SUCESSO.");
} catch (SQLException e) {
System.out.println("ERRO AO CADASTRAR USUÁRIO.");
//e.printStackTrace();
}
}
And how could I create this other layer... could give me a touch?
– Carlos Leandro Ferreira de Alm
although not the scope of your question, I added. If you don’t also have a way to recover from a Sqlexception, create an exception of Runtime (not checked) yours, and launch it from within the DAO. It also has other important details on how not to handle transactions within a DAO method, but now it’s not the case :)
– wryel