-
Notifications
You must be signed in to change notification settings - Fork 0
/
PetControl.java
84 lines (73 loc) · 2.43 KB
/
PetControl.java
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
72
73
74
75
76
77
78
79
80
81
82
83
84
package edu.curso;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
public class PetControl {
private static final String URL = "jdbc:mariadb://localhost/petshop?allowMultiQueries=true";
private static final String USER = "root";
private static final String PASS = "";
public PetControl() {
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch (ClassNotFoundException e) {
alertError("Erro de database", "Erro ao carregar a classe JDBC", e.getMessage());
}
}
private void alertError(String title, String header, String content) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle(title);
alert.setHeaderText(header);
alert.setContentText(content);
alert.showAndWait();
}
public void adicionar(Pet p) {
try {
Connection con = DriverManager.getConnection(URL, USER, PASS);
String sql = "INSERT INTO pet (id, nome, raca, peso, nascimento) "
+ "VALUES (0, ?, ?, ?, ?)";
PreparedStatement stm = con.prepareStatement(sql);
stm.setString(1, p.getNome());
stm.setString(2, p.getRaca());
stm.setDouble(3, p.getPeso());
stm.setDate(4, java.sql.Date.valueOf(p.getNascimento()));
stm.executeUpdate();
// Statement stm = con.createStatement();
//
// String sql = "INSERT INTO pet (id, nome, raca, peso, nascimento) " +
// "VALUES (0, '" + p.getNome() +
// "', '" + p.getRaca() +
// "', " + p.getPeso() +
// ", '" + dtf.format(p.getNascimento()) + "')";
// stm.executeUpdate(sql);
con.close();
} catch (SQLException e) {
alertError("Erro de database", "Erro ao acessar o banco de dados", e.getMessage());
}
}
public Pet pesquisarPorNome(String nome) {
try {
Connection con = DriverManager.getConnection(URL, USER, PASS);
String sql = "SELECT * FROM pet WHERE nome like ?";
PreparedStatement stm = con.prepareStatement(sql);
stm.setString(1, "%" + nome + "%");
ResultSet rs = stm.executeQuery();
if (rs.first()) {
Pet p = new Pet();
p.setNome(rs.getString("nome"));
p.setRaca(rs.getString("raca"));
p.setPeso(rs.getDouble("peso"));
p.setNascimento(rs.getDate("nascimento").toLocalDate());
return p;
}
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}