-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContatoDao.java
More file actions
71 lines (60 loc) · 2.18 KB
/
ContatoDao.java
File metadata and controls
71 lines (60 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package connectionFactory;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ContatoDao {
// a conexão com o banco de dados
private Connection connection;
public ContatoDao() throws ClassNotFoundException {
connection = new ConnectionFactory().getConnection("localhost", "test", "root", "");
}
public void adiciona(Contato contato) {
String sql = "insert into contatos " +
"(nome,email,endereco,dataNascimento)" +
" values (?,?,?,?)";
try {
// prepared statement para inserção
PreparedStatement stmt = connection.prepareStatement(sql);
// seta os valores
stmt.setString(1,contato.getNome());
stmt.setString(2,contato.getEmail());
stmt.setString(3,contato.getEndereco());
stmt.setDate(4, new Date(
contato.getDataNascimento().getTimeInMillis()));
// executa
stmt.execute();
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void altera(Contato contato) {
String sql = "update contatos set nome=?, email=?, endereco=?," +
"dataNascimento=? where 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);
}
}
public void remove(Contato contato) {
try {
PreparedStatement stmt = connection
.prepareStatement("delete from contatos where id=?");
stmt.setLong(1, contato.getId());
stmt.execute();
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}