package com.llgc.dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.llgc.modele.pojo.POJOVoiture; public class DAOVoiture implements IDAO { @Override public void create(POJOVoiture entite) throws ClassNotFoundException, SQLException { try (PreparedStatement pstmt = DAOConnection.getInstance().getConnexion().prepareStatement( "INSERT INTO donnees (nom, poids, marque) VALUES (?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) { pstmt.setString(1, entite.getNom()); pstmt.setInt(2, entite.getPoids()); pstmt.setString(3, entite.getMarque()); pstmt.executeUpdate(); ResultSet rs = pstmt.getGeneratedKeys(); if (rs.next()) { entite.setId(rs.getInt(1)); } else { throw new SQLException("Impossible d'obtenir le numéro de la voiture via la base de donnée voiture."); } return; } } @Override public POJOVoiture read(int id) throws ClassNotFoundException, SQLException { try (PreparedStatement pstmt = DAOConnection.getInstance().getConnexion() .prepareStatement("SELECT nom, poids, marque FROM donnees WHERE id = ?")) { POJOVoiture retour = new POJOVoiture(id); pstmt.setInt(1, id); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { retour = new POJOVoiture(id); retour.setNom(rs.getString(1)); retour.setPoids(rs.getInt(2)); retour.setMarque(rs.getString(3)); } return retour; } } @Override public void update(POJOVoiture entite) throws ClassNotFoundException, SQLException { try (PreparedStatement pstmt = DAOConnection.getInstance().getConnexion() .prepareStatement("UPDATE donnees SET nom = ?, poids = ? , marque = ? WHERE id = ?")) { pstmt.setString(1, entite.getNom()); pstmt.setInt(2, entite.getPoids()); pstmt.setString(3, entite.getMarque()); pstmt.setInt(4, entite.getId()); pstmt.executeUpdate(); } } public void updateNom(int id, String nom) throws ClassNotFoundException, SQLException { try (PreparedStatement pstmt = DAOConnection.getInstance().getConnexion() .prepareStatement("UPDATE donnees SET nom = ? WHERE id = ?")) { pstmt.setString(1, nom); pstmt.setInt(2, id); pstmt.executeUpdate(); } } public void updatePoids(int id, int poids) throws ClassNotFoundException, SQLException { try (PreparedStatement pstmt = DAOConnection.getInstance().getConnexion() .prepareStatement("UPDATE donnees SET poids = ? WHERE id = ?")) { pstmt.setInt(1, poids); pstmt.setInt(2, id); pstmt.executeUpdate(); } } public void updateMarque(int id, String marque) throws ClassNotFoundException, SQLException { try (PreparedStatement pstmt = DAOConnection.getInstance().getConnexion() .prepareStatement("UPDATE donnees SET marque = ? WHERE id = ?")) { pstmt.setString(1, marque); pstmt.setInt(2, id); pstmt.executeUpdate(); } } @Override public void delete(int id) throws ClassNotFoundException, SQLException { try (PreparedStatement pstmt = DAOConnection.getInstance().getConnexion() .prepareStatement("DELETE FROM donnees WHERE id = ?")) { pstmt.setInt(1, id); pstmt.executeUpdate(); } } }