Skip to content

Commit 34800f0

Browse files
committed
ContatoDAO renomeado para ContatoDAOImpl;
Interface ContatoDAO adicionada, ContatoDAOImpl implementando ContatoDAO; ConnectionFactory não mais com métodos estáticos; Métodos que fazem chamadas ao banco de dados agora iniciam-se abrindo uma nova conexão e fecham essa conexão ao final.
1 parent e0ecc7d commit 34800f0

File tree

6 files changed

+278
-226
lines changed

6 files changed

+278
-226
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/nbproject/private/
2+
/build/

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ Projeto simples desenvolvido no NetBeans utilizando a linguagem Java fazendo int
55
As operações exemplificadas nesse projeto são as de: inserção, leitura, alteração e remoção (CRUD) de contatos no banco de dados MySQL.
66

77
* Downloads: https://github.com/iagocolodetti/JavaDBExemplo/releases
8-
* [Arquivo de Script MySQL](https://github.com/iagocolodetti/JavaDBExemplo/releases/download/v1.1/contatodb.sql "contatodb.sql")
9-
* [Driver Necessário](https://github.com/iagocolodetti/JavaDBExemplo/releases/download/v1.1/mysql-connector-java-5.1.23-bin.jar "mysql-connector-java-5.1.23-bin.jar")
10-
* [Código-Fonte](https://github.com/iagocolodetti/JavaDBExemplo/archive/v1.1.zip "v1.1.zip")
8+
* [Arquivo de Script MySQL](https://github.com/iagocolodetti/JavaDBExemplo/releases/download/v1.2/contatodb.sql "contatodb.sql")
9+
* [Driver Necessário](https://github.com/iagocolodetti/JavaDBExemplo/releases/download/v1.2/mysql-connector-java-5.1.23-bin.jar "mysql-connector-java-5.1.23-bin.jar")
10+
* [Código-Fonte](https://github.com/iagocolodetti/JavaDBExemplo/archive/v1.2.zip "v1.2.zip")
1111
<br/>
1212
<h3>Conectando o Banco de Dados MySQL no NetBeans</h3>
1313

src/ConnectionFactory.java

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,16 @@
1111
*/
1212
public class ConnectionFactory {
1313

14-
private static final String DRIVER = "com.mysql.jdbc.Driver";
14+
private final String DRIVER = "com.mysql.jdbc.Driver";
1515

1616
// URL de acesso ao banco de dados.
17-
private static final String URL = "jdbc:mysql://localhost:3306/contatodb";
17+
private final String URL = "jdbc:mysql://localhost:3306/contatodb";
1818
// Nome de usuário para acesso ao banco de dados.
19-
private static final String USER = "root";
19+
private final String USER = "root";
2020
// Senha de usuário para acesso ao banco de dados.
21-
private static final String PASS = "root";
21+
private final String PASS = "root";
2222

23-
public static Connection getConnection() {
23+
public Connection getConnection() {
2424

2525
try {
2626
Class.forName(DRIVER);
@@ -31,7 +31,7 @@ public static Connection getConnection() {
3131
return null;
3232
}
3333

34-
public static void closeConnection(Connection con) {
34+
public void closeConnection(Connection con) {
3535

3636
try {
3737
if (con != null) {
@@ -42,8 +42,9 @@ public static void closeConnection(Connection con) {
4242
}
4343
}
4444

45-
public static void closeConnection(PreparedStatement ps) {
45+
public void closeConnection(Connection con, PreparedStatement ps) {
4646

47+
closeConnection(con);
4748
try {
4849
if (ps != null) {
4950
ps.close();
@@ -53,9 +54,9 @@ public static void closeConnection(PreparedStatement ps) {
5354
}
5455
}
5556

56-
public static void closeConnection(PreparedStatement ps, ResultSet rs) {
57+
public void closeConnection(Connection con, PreparedStatement ps, ResultSet rs) {
5758

58-
closeConnection(ps);
59+
closeConnection(con, ps);
5960
try {
6061
if (rs != null) {
6162
rs.close();

src/ContatoDAO.java

Lines changed: 17 additions & 211 deletions
Original file line numberDiff line numberDiff line change
@@ -1,228 +1,34 @@
11

2-
import java.sql.Connection;
3-
import java.sql.PreparedStatement;
4-
import java.sql.ResultSet;
52
import java.sql.SQLException;
6-
import java.util.ArrayList;
73
import java.util.List;
84

95
/**
106
*
117
* @author iagocolodetti
128
*/
13-
public class ContatoDAO {
9+
public interface ContatoDAO {
1410

15-
private Connection con = null;
11+
public void add(Contato contato)
12+
throws SQLException;
1613

17-
public ContatoDAO() {
18-
con = ConnectionFactory.getConnection();
19-
}
14+
public Contato getContato(int id)
15+
throws ContatoNaoExisteException, SQLException;
2016

21-
// <editor-fold defaultstate="collapsed" desc="Comando(s) de Criação/Escrita (CREATE)">
22-
public void add(Contato contato) throws SQLException {
17+
public List<Contato> getContatosPorNome(String nome)
18+
throws ContatoNaoExisteException, SQLException;
2319

24-
PreparedStatement ps = null;
20+
public List<Contato> getContatosPorTelefone(String telefone)
21+
throws ContatoNaoExisteException, SQLException;
2522

26-
try {
27-
ps = con.prepareStatement("INSERT INTO contato(nome, telefone, email) VALUES(?, ?, ?)");
28-
ps.setString(1, contato.getNome());
29-
ps.setString(2, contato.getTelefone());
30-
ps.setString(3, contato.getEmail());
23+
public List<Contato> getContatosPorEmail(String email)
24+
throws ContatoNaoExisteException, SQLException;
3125

32-
ps.executeUpdate();
33-
} catch (SQLException e) {
34-
throw new SQLException("Não foi possível adicionar o contato.");
35-
} finally {
36-
ConnectionFactory.closeConnection(ps);
37-
}
38-
}
39-
// </editor-fold>
26+
public List<Contato> getContatos()
27+
throws ContatoNaoExisteException, SQLException;
4028

41-
// <editor-fold defaultstate="collapsed" desc="Comando(s) de Leitura/Busca (READ)">
42-
public Contato getContato(int id) throws ContatoNaoExisteException, SQLException {
29+
public void update(Contato contato)
30+
throws ContatoNaoExisteException, SQLException;
4331

44-
PreparedStatement ps = null;
45-
ResultSet rs = null;
46-
47-
Contato contato = null;
48-
49-
try {
50-
ps = con.prepareStatement("SELECT * FROM contato WHERE id = ?");
51-
ps.setInt(1, id);
52-
rs = ps.executeQuery();
53-
54-
while (rs.next()) {
55-
contato = new Contato(rs.getInt("id"), rs.getString("nome"), rs.getString("telefone"), rs.getString("email"));
56-
}
57-
58-
if (contato == null) {
59-
throw new ContatoNaoExisteException("Não existe contato com esse ID.");
60-
}
61-
} catch (SQLException e) {
62-
throw new SQLException("Não foi possível buscar o contato.");
63-
} finally {
64-
ConnectionFactory.closeConnection(ps, rs);
65-
}
66-
67-
return contato;
68-
}
69-
70-
public List<Contato> getContatosPorNome(String nome) throws ContatoNaoExisteException, SQLException {
71-
72-
PreparedStatement ps = null;
73-
ResultSet rs = null;
74-
75-
List<Contato> contatos = new ArrayList<>();
76-
77-
try {
78-
ps = con.prepareStatement("SELECT * FROM contato WHERE nome LIKE ?");
79-
ps.setString(1, "%" + nome + "%");
80-
rs = ps.executeQuery();
81-
82-
while (rs.next()) {
83-
Contato contato = new Contato(rs.getInt("id"), rs.getString("nome"), rs.getString("telefone"), rs.getString("email"));
84-
contatos.add(contato);
85-
}
86-
87-
if (contatos.isEmpty()) {
88-
throw new ContatoNaoExisteException("Não existem contatos com esse nome ou parte dele.");
89-
}
90-
} catch (SQLException e) {
91-
throw new SQLException("Não foi possível buscar os contatos.");
92-
} finally {
93-
ConnectionFactory.closeConnection(ps, rs);
94-
}
95-
96-
return contatos;
97-
}
98-
99-
public List<Contato> getContatosPorTelefone(String telefone) throws ContatoNaoExisteException, SQLException {
100-
101-
PreparedStatement ps = null;
102-
ResultSet rs = null;
103-
104-
List<Contato> contatos = new ArrayList<>();
105-
106-
try {
107-
ps = con.prepareStatement("SELECT * FROM contato WHERE telefone LIKE ?");
108-
ps.setString(1, "%" + telefone + "%");
109-
rs = ps.executeQuery();
110-
111-
while (rs.next()) {
112-
Contato contato = new Contato(rs.getInt("id"), rs.getString("nome"), rs.getString("telefone"), rs.getString("email"));
113-
contatos.add(contato);
114-
}
115-
116-
if (contatos.isEmpty()) {
117-
throw new ContatoNaoExisteException("Não existem contatos com esse telefone ou parte dele.");
118-
}
119-
} catch (SQLException e) {
120-
throw new SQLException("Não foi possível buscar os contatos.");
121-
} finally {
122-
ConnectionFactory.closeConnection(ps, rs);
123-
}
124-
125-
return contatos;
126-
}
127-
128-
public List<Contato> getContatosPorEmail(String email) throws ContatoNaoExisteException, SQLException {
129-
130-
PreparedStatement ps = null;
131-
ResultSet rs = null;
132-
133-
List<Contato> contatos = new ArrayList<>();
134-
135-
try {
136-
ps = con.prepareStatement("SELECT * FROM contato WHERE email LIKE ?");
137-
ps.setString(1, "%" + email + "%");
138-
rs = ps.executeQuery();
139-
140-
while (rs.next()) {
141-
Contato contato = new Contato(rs.getInt("id"), rs.getString("nome"), rs.getString("telefone"), rs.getString("email"));
142-
contatos.add(contato);
143-
}
144-
145-
if (contatos.isEmpty()) {
146-
throw new ContatoNaoExisteException("Não existem contatos com esse e-mail ou parte dele.");
147-
}
148-
} catch (SQLException e) {
149-
throw new SQLException("Não foi possível buscar os contatos.");
150-
} finally {
151-
ConnectionFactory.closeConnection(ps, rs);
152-
}
153-
154-
return contatos;
155-
}
156-
157-
public List<Contato> getContatos() throws ContatoNaoExisteException, SQLException {
158-
159-
PreparedStatement ps = null;
160-
ResultSet rs = null;
161-
162-
List<Contato> contatos = new ArrayList<>();
163-
164-
try {
165-
ps = con.prepareStatement("SELECT * FROM contato");
166-
rs = ps.executeQuery();
167-
168-
while (rs.next()) {
169-
Contato contato = new Contato(rs.getInt("id"), rs.getString("nome"), rs.getString("telefone"), rs.getString("email"));
170-
contatos.add(contato);
171-
}
172-
173-
if (contatos.isEmpty()) {
174-
throw new ContatoNaoExisteException("Não existem contatos.");
175-
}
176-
} catch (SQLException e) {
177-
throw new SQLException("Não foi possível buscar os contatos.");
178-
} finally {
179-
ConnectionFactory.closeConnection(ps, rs);
180-
}
181-
182-
return contatos;
183-
}
184-
// </editor-fold>
185-
186-
// <editor-fold defaultstate="collapsed" desc="Comando(s) de Atualização/Alteração (UPDATE)">
187-
public void update(Contato contato) throws ContatoNaoExisteException, SQLException {
188-
189-
PreparedStatement ps = null;
190-
191-
try {
192-
ps = con.prepareStatement("UPDATE contato SET nome = ?, telefone = ?, email = ? WHERE id = ?");
193-
ps.setString(1, contato.getNome());
194-
ps.setString(2, contato.getTelefone());
195-
ps.setString(3, contato.getEmail());
196-
ps.setInt(4, contato.getId());
197-
198-
if (ps.executeUpdate() == 0) throw new ContatoNaoExisteException("Não existe contato com esse ID.");
199-
} catch (SQLException e) {
200-
throw new SQLException("Não foi possível alterar/atualizar o contato.");
201-
} finally {
202-
ConnectionFactory.closeConnection(ps);
203-
}
204-
}
205-
// </editor-fold>
206-
207-
// <editor-fold defaultstate="collapsed" desc="Comando(s) de Exclusão/Remoção (DELETE)">
208-
public void delete(int id) throws ContatoNaoExisteException, SQLException {
209-
210-
PreparedStatement ps = null;
211-
212-
try {
213-
ps = con.prepareStatement("DELETE FROM contato WHERE id = ?");
214-
ps.setInt(1, id);
215-
216-
if (ps.executeUpdate() == 0) throw new ContatoNaoExisteException();
217-
} catch (SQLException e) {
218-
throw new SQLException("Não foi possível excluir/remover o contato.");
219-
} finally {
220-
ConnectionFactory.closeConnection(ps);
221-
}
222-
}
223-
// </editor-fold>
224-
225-
public void close() {
226-
ConnectionFactory.closeConnection(con);
227-
}
32+
public void delete(int id)
33+
throws ContatoNaoExisteException, SQLException;
22834
}

0 commit comments

Comments
 (0)