Package br.com.humberto.jdb.modelo

Source Code of br.com.humberto.jdb.modelo.ContatoDao

package br.com.humberto.jdb.modelo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import br.com.humberto.jdbc.ConnectionFactory;

public class ContatoDao {
  private Connection connection;

  public ContatoDao() {
    this.connection = new ConnectionFactory().getConnection();
  }

  public void Adiciona(Contato contato) throws DAOException {
    try {

      System.out.println("Conex�o aberta!");

      String sql = "insert into contatos "
          + "(nome,email,endereco,dataNascimento) "
          + "values (?,?,?,?)";

      PreparedStatement stmt = this.connection.prepareStatement(sql);
      stmt.setString(1, contato.getNome());
      stmt.setString(2, contato.getEmail());
      stmt.setString(3, contato.getEndereco());

      java.sql.Date dataParaGravar = new java.sql.Date(Calendar
          .getInstance().getTimeInMillis());
      stmt.setDate(4, dataParaGravar);
      stmt.execute();
      stmt.close();

    } catch (SQLException e) {
      throw new RuntimeException(e);
    }

  }

  public List<Contato> getLista() {

    try {
      List<Contato> contatos = new ArrayList<Contato>();
      PreparedStatement stmt = this.connection
          .prepareStatement("Select * from contatos");

      ResultSet rs = stmt.executeQuery();

      while (rs.next()) {
        Contato contato = new Contato();
        contato.setId(rs.getLong("id"));
        contato.setNome(rs.getString("nome"));
        contato.setEmail(rs.getString("email"));
        contato.setEndereco(rs.getString("endereco"));
        Calendar data = Calendar.getInstance();
        data.setTime(rs.getDate("dataNascimento"));
        contato.setDataNascimento(data);
        contatos.add(contato);
      }
      rs.close();
      stmt.close();
      return contatos;
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }

  }
}
TOP

Related Classes of br.com.humberto.jdb.modelo.ContatoDao

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.