How do I make change in the database using the method changes in a ClassAlertFoundation. Do I use the gets and sets of the template to change the data? Do I need to use the SearchId (int id) method to return an object?
//pesquisa pelo id e retorna um contato
public Contato pesquisarId(int id) {
try {
String sql = "select * from contatos where id = " + id;
Contato contato = new Contato();
PreparedStatement stmt = this.connection.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
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);
}
rs.close();
stmt.close();
return contato;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//altera
public void altera(Contato contato) {
String sql = "update contatos set nome=?, email=? where id = id";
try {
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, contato.getNome());
stmt.setString(2, contato.getEmail());
stmt.setString(3, contato.getEndereco());
stmt.setDate(4, new Date(contato.getDataNascimento().getTimeInMillis()));
stmt.setLong(5, contato.getId());
stmt.execute();
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
In short how would the class change?
package br.com.caelum.jdbc.teste;
import br.com.caelum.jdbc.dao.ContatoDao;
import br.com.caelum.jdbc.modelo.Contato;
public class TesteAltera {
public static void main(String[] args) {
ContatoDao dao = new ContatoDao();
Contato contato = dao.pesquisarId(1);
dao.altera(contato);
}
}