Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private Connection obterConexao()
- throws ClassNotFoundException, SQLException {
- Connection conn = null;
- // Passo 1: Registrar driver JDBC
- Class.forName("com.mysql.jdbc.Driver");
- // Passo 2: Obter a conexao
- conn = DriverManager.getConnection(
- "jdbc:mysql://localhost:3306/agendabd",
- "root",
- "");
- return conn;
- }
- public void incluir(Pessoa p, Contato email, Contato telefone) throws ClassNotFoundException, SQLException {
- String query = "INSERT INTO pessoa (nome, dtnascimento) VALUES (?, ?)";
- String queryContato = "INSERT INTO contato(tipo, valor, idpessoa) VALUES (?, ?, ?)";
- try (Connection conn = obterConexao()) {
- // DESLIGAR O AUTO COMMIT
- conn.setAutoCommit(false);
- // ADICIONAR O Statement.RETURN_GENERATED_KEYS NA CHAMADA DO MÉTODO
- try (PreparedStatement stmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
- stmt.setString(1, p.getNome());
- stmt.setDate(2, new java.sql.Date(p.getDtNascimento().getTime()));
- stmt.executeUpdate();
- // TENTA RECUPERAR O ID GERADO NO BANCO DE DADOS
- try (ResultSet chaves = stmt.getGeneratedKeys()) {
- if (chaves.next()) {
- long idPessoa = chaves.getLong(1);
- // USA O ID RECUPERADO PARA SALVAR 2 CONTATOS ASSOCIADOS NO BD
- try (PreparedStatement stmt2 = conn.prepareStatement(queryContato)) {
- stmt2.setInt(1, email.getTipo());
- stmt2.setString(2, email.getValor());
- stmt2.setLong(3, idPessoa);
- stmt2.executeUpdate();
- }
- try (PreparedStatement stmt3 = conn.prepareStatement(queryContato)) {
- stmt3.setInt(1, telefone.getTipo());
- stmt3.setString(2, telefone.getValor());
- stmt3.setLong(3, idPessoa);
- stmt3.executeUpdate();
- }
- // EFETIVA TODAS AS OPERAÇÕES REALIZADAS
- conn.commit();
- }
- }
- } catch (SQLException e) {
- // CASO OCORRA ERRO, DESFAZ TODAS AS OPERAÇÕES
- conn.rollback();
- System.out.println(e.getLocalizedMessage());
- throw e;
- }
- }
- }
Add Comment
Please, Sign In to add comment