1
\$\begingroup\$

I would like to simplify my code when I add an entry. All is OK for 1 table (table = "ecole"). I can add an entry without problem.

My problem is that I will wish to add a second table named "nom" in my CRUD system, but this is complicated in my code... :-(

Do you have any suggestions?

public class EcoleBD {

    public static Connection getConnection(){
        Connection con=null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/exemple","root","");
        }catch(Exception e){System.out.println(e);}
        return con;
    }
    public static int save(Ecole u){
        int status=0;
        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement(
                    "insert into ecole(nom_ecole, adresse_ecole) values(?,?)");
            ps.setString(1,u.getNom_ecole());
            ps.setString(2,u.getAdresse_ecole());
            status=ps.executeUpdate();
        }catch(Exception e){System.out.println(e);}
        return status;
    }

    public static List<Ecole> getAllRecords(){
        List<Ecole> list=new ArrayList<Ecole>();

        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement("select * from ecole");
            ResultSet rs=ps.executeQuery();
            while(rs.next()){
                Ecole u=new Ecole();
                u.setPk_ecole(rs.getInt("pk_ecole"));
                u.setNom_ecole(rs.getString("nom_ecole"));
                u.setAdresse_ecole(rs.getString("adresse_ecole"));
                list.add(u);
            }
        }catch(Exception e){System.out.println(e);}
        return list;
    }
    public static Ecole getRecordById(int pk_ecole){
        Ecole u=null;
        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement("select * from ecole where pk_ecole=?");
            ps.setInt(1,pk_ecole);
            ResultSet rs=ps.executeQuery();
            while(rs.next()){
                u=new Ecole();
                u.setPk_ecole(rs.getInt("pk_ecole"));
                u.setNom_ecole(rs.getString("nom_ecole"));
                u.setAdresse_ecole(rs.getString("adresse_ecole"));
            }
        }catch(Exception e){System.out.println(e);}
        return u;
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.