1
How I change the database using the method changes in a Testaaltera class. I use the model gets and sets to change the data? I need to use the Search(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);
}
}
Summarizing how it would look the class alters?
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);
}
}
For it to persist new data in the update command, you simply have to assign new values to the 'contact', no?
contato.setNome("Fulano");
etc....– Julian
AEE was successful
– Gabriel Faria
Gabriel, I will answer your question so that the question can be closed. Note: Do not set a new id for the record you searched from the table. If possible, please evaluate my response.
– Julian
@Gabrielfaria does not need you to put as title that was SOLVED your problem.
– viana