FornoDao Java Class: JDBC CRUD Operations for Oven Management
Classified in Computers
Written on in
English with a size of 3.25 KB
FornoDao Java Class: JDBC CRUD Operations
The following FornoDao class is a Data Access Object (DAO) that performs CRUD operations on the FORNO table using JDBC.
public class FornoDao {
private Connection connection;
public FornoDao() {
this.connection = new ConnectionFactory().getConnection();
}
public void remover(Forno f) {
String sql = "DELETE FROM FORNO WHERE FOR_NUM=" + f.getNumero();
try {
Statement stm = this.connection.createStatement();
stm.execute(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
public void inserir(Forno f) {
String sql = "INSERT INTO FORNO(FOR_NUM, FOR_TEMP, FOR_LIGADO, FOR_VOLUME) ";
sql += "VALUES (" + f.getNumero() + ", " + f.getTemperatura() + ", " + f.isLigado() + ", " + f.getVolume() + ")";
try {
Statement stm = this.connection.createStatement();
stm.execute(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
public void insert(Forno f) {
String sql = "INSERT INTO FORNO(FOR_NUM, FOR_TEMP, FOR_LIGADO, FOR_VOLUME) VALUES (?,?,?,?)";
try {
PreparedStatement stmp = this.connection.prepareStatement(sql);
stmp.setInt(1, f.getNumero());
stmp.setInt(2, f.getTemperatura());
stmp.setBoolean(3, f.isLigado());
stmp.setInt(4, f.getVolume());
stmp.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
public void update(Forno f) {
String sql = "UPDATE FORNO SET FOR_TEMP=?, FOR_LIGADO=?, FOR_VOLUME=? WHERE FOR_NUM=?";
try {
PreparedStatement stm = this.connection.prepareStatement(sql);
stm.setInt(1, f.getTemperatura());
stm.setBoolean(2, f.isLigado());
stm.setInt(3, f.getVolume());
stm.setInt(4, f.getNumero());
stm.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
public Forno getInstance(int numeroDoForno) {
Forno forno = new Forno(100);
String sql = "SELECT FORNO.* FROM FORNO WHERE FOR_NUM=?";
try {
PreparedStatement stm = this.connection.prepareStatement(sql);
stm.setInt(1, numeroDoForno);
ResultSet rs = stm.executeQuery();
while (rs.next()) {
forno.setNumero(rs.getInt("FOR_NUM"));
forno.setTemperatura(rs.getInt("FOR_TEMP"));
forno.setLigado(rs.getBoolean("FOR_LIGADO"));
forno.setVolume(rs.getInt("FOR_VOLUME"));
}
rs.close();
stm.close();
} catch (Exception e) {
e.printStackTrace();
}
return forno;
}
}
Security Note: SQL Injection Risk
The remover and inserir methods build SQL statements by concatenating values directly into the query string. This makes them vulnerable to SQL injection. Prefer the PreparedStatement approach used in insert, update, and getInstance, which keeps SQL and data separate.