Guest User

Untitled

a guest
Oct 11th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. private Connection obterConexao()
  2. throws ClassNotFoundException, SQLException {
  3. Connection conn = null;
  4.  
  5. // Passo 1: Registrar driver JDBC
  6. Class.forName("com.mysql.jdbc.Driver");
  7. // Passo 2: Obter a conexao
  8. conn = DriverManager.getConnection(
  9. "jdbc:mysql://localhost:3306/agendabd",
  10. "root",
  11. "");
  12. return conn;
  13. }
  14.  
  15. public void incluir(Pessoa p, Contato email, Contato telefone) throws ClassNotFoundException, SQLException {
  16.  
  17. String query = "INSERT INTO pessoa (nome, dtnascimento) VALUES (?, ?)";
  18. String queryContato = "INSERT INTO contato(tipo, valor, idpessoa) VALUES (?, ?, ?)";
  19.  
  20. try (Connection conn = obterConexao()) {
  21. // DESLIGAR O AUTO COMMIT
  22. conn.setAutoCommit(false);
  23.  
  24. // ADICIONAR O Statement.RETURN_GENERATED_KEYS NA CHAMADA DO MÉTODO
  25. try (PreparedStatement stmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
  26. stmt.setString(1, p.getNome());
  27. stmt.setDate(2, new java.sql.Date(p.getDtNascimento().getTime()));
  28. stmt.executeUpdate();
  29.  
  30. // TENTA RECUPERAR O ID GERADO NO BANCO DE DADOS
  31. try (ResultSet chaves = stmt.getGeneratedKeys()) {
  32. if (chaves.next()) {
  33. long idPessoa = chaves.getLong(1);
  34.  
  35. // USA O ID RECUPERADO PARA SALVAR 2 CONTATOS ASSOCIADOS NO BD
  36. try (PreparedStatement stmt2 = conn.prepareStatement(queryContato)) {
  37. stmt2.setInt(1, email.getTipo());
  38. stmt2.setString(2, email.getValor());
  39. stmt2.setLong(3, idPessoa);
  40. stmt2.executeUpdate();
  41. }
  42. try (PreparedStatement stmt3 = conn.prepareStatement(queryContato)) {
  43. stmt3.setInt(1, telefone.getTipo());
  44. stmt3.setString(2, telefone.getValor());
  45. stmt3.setLong(3, idPessoa);
  46. stmt3.executeUpdate();
  47. }
  48.  
  49. // EFETIVA TODAS AS OPERAÇÕES REALIZADAS
  50. conn.commit();
  51. }
  52. }
  53.  
  54. } catch (SQLException e) {
  55. // CASO OCORRA ERRO, DESFAZ TODAS AS OPERAÇÕES
  56. conn.rollback();
  57. System.out.println(e.getLocalizedMessage());
  58. throw e;
  59. }
  60. }
  61. }
Add Comment
Please, Sign In to add comment