Publicité

1145709.ppt

19 Mar 2023
Publicité

Contenu connexe

Publicité

1145709.ppt

  1. CONNEXION BASE DE DONNÉES Mini-projets Java-BD 2011-2012 Wael Mallek Imed Amri
  2. JDBC API ?  API d’interaction avec un SGBD contenant :  un ensemble de classes et d’interfaces  ne fournit pas les classes qui implantent les interfaces  Permet de:  Établir une connexion avec un SGBD  Envoyer des requêtes SQL  Récupérer des résultats de requêtes
  3. Drivers ?  Drivers  chaque SGBD utilise un pilote (driver) qui lui est propre et qui permet de convertir les requêtes JDBC dans le langage natif du SGBD  le driver est un ensemble de classes qui implantent les interfaces de JDBC  les drivers sont le lien entre le programme Java et le SGBD
  4. Base MySQL  Créer une base mysql ‘esprit’
  5. Projet Java  Créer un nouveau Projet : Java Application  Ajouter la Librairie MySQL JDBC Driver
  6. Méthode Main  Les Attribues de la classes :  static String url = "jdbc:mysql://localhost/esprit";  static String user = "root";  static String pwd = "";  static Connection conn;  static Statement ste;
  7. Méthode Main  Charger le Driver  Class.forName("com.mysql.jdbc.Driver");  Etablir une connexion  conn = DriverManager.getConnection(url, user, pwd);  Traiter les exceptions  ClassNotFoundException  SQLException
  8. Méthode Main  Les Attribues de la classes :  static String url = "jdbc:mysql://localhost/esprit";  static String user = "root";  static String pwd = "";  static Connection conn;  static Statement ste;
  9. Méthode Main  Créer un STATEMENT  ste = conn.createStatement();  Requete SQL d’ajout  String req = "Insert into personne values("+null+",'A2','3info')";  Executer la Requete  ste.executeUpdate(req) (insert, update, delete)  ste.executeQuery(req) select
  10. Méthodes CRUD  Créer 4 méthodes static :  static void Ajouter(String Nom, String Prenom){ }  static void UpdatePrenom(int id, String Prenom){ }  static void Delete(int id){ }  static void AfficherAll(){ } Utiliser le ResultSet pour récupérer le résultat de executeQuery  ajouter throws SQLException pour chaque Methode
  11. Correspondance Java / BD Type JDBC/SQL Méthode Java  CHAR, VARCHAR getString()  BINARY, VARBINARY getBytes()  BIT getBoolean()  INTEGER getInt()  BIGINT getLong()  SMALLINT getShort()  REAL getFloat()  DOUBLE, FLOAT getDouble()  DATE getDate()  TIME getTime()  TIME STAMP getTimeStamp()
  12. Design Pattern  Singleton : permet d’instancier l’objet qu’une seule fois.
  13. Design Pattern  Singleton : (dans notre cas)  un attribut statique  private static Connection conn;  un constructeur déclaré en privé  private MyConnection() { … }  une méthode statique servant de pseudo- constructeur  public static Connection getInstance() { … }
  14. Design Pattern  DAO : Permet de regrouper les accès aux données persistantes dans des classes à part.  Séparation entre la couche Métier et les données.
  15. Les Packages  Créer 4 packages  Entite  Classe Personne  DAO  Classe PersonneDAO  Metier  Classe MyConnection  Test  Classe Main
  16. Metier  private static Connection conn;  private MyConnection() { }  public static Connection getInstance(){ if(conn==null) { MyConnection aa = new MyConnection(); } return conn; }
  17. Entite  Créer une classe Personne  private int id;  private String nom;  private String prenom;  Générer les constructeurs  Générer les Getters et les Setters
  18. DAO  Créer une Classe PersonneDAO  Connection conn=MyConnection.getInstance();  Statement ste;  Méthodes CRUD  public int Ajouter (Personne p)  public Vector<Personne> readAll()  public boolean update (Personne p)  public boolean delete (int id)  public Personne findById (int id)
  19. Ajouter public int Ajouter(Personne p) throws SQLException { int cle=0; ste=conn.createStatement(); String reqinsert ="INSERT INTO `personne` ( `nom` , `prenom` ) " + "VALUES ('"+p.getNom()+"', '"+p.getPrenom()+"');"; ste.executeUpdate(reqinsert); ResultSet rs=ste.getGeneratedKeys(); while (rs.next()) { cle=rs.getInt(1); } return cle; }
  20. DAO  Créer une Classe PersonneDAO  Connection conn=MyConnection.getInstance();  Statement ste;  Méthodes CRUD  public int Ajouter (Personne p)  public Vector<Personne> readAll()  public boolean update (Personne p)  public boolean delete (int id)  public Personne findById (int id)
  21. readAll() public Vector<Personne> readAll() throws SQLException{ Vector<Personne> v=new Vector<Personne>(); Statement ste=conn.createStatement(); String req="Select * from personne;"; ResultSet rs=ste.executeQuery(req); while (rs.next()) { Personne p=new Personne(rs.getInt(1), rs.getString(2), rs.getString(3)); v.add(p); } return v; }
  22. DAO  Créer une Classe PersonneDAO  Connection conn=MyConnection.getInstance();  Statement ste;  Méthodes CRUD  public int Ajouter (Personne p)  public Vector<Personne> readAll()  public boolean update (Personne p)  public boolean delete (int id)  public Personne findById (int id)
  23. update public boolean update(Personne p) throws SQLException { boolean test=false; Statement ste=conn.createStatement(); String req="UPDATE `j2me`.`personne` SET `nom` ='"+p.getNom()+"' WHERE `personne`.`id` ="+p.getId()+";"; int res=ste.executeUpdate(req); if(res!=0) test=true; return test; }
  24. DAO  Créer une Classe PersonneDAO  Connection conn=MyConnection.getInstance();  Statement ste;  Méthodes CRUD  public int Ajouter (Personne p)  public Vector<Personne> readAll()  public boolean update (Personne p)  public boolean delete (int id)  public Personne findById (int id)
  25. delete public boolean delete(int id) throws SQLException {boolean test=false; Statement ste=conn.createStatement(); String req="DELETE FROM `j2me`.`personne` WHERE `personne`.`id` ='"+id+"';"; int res=ste.executeUpdate(req); if(res!=0) test=true; return test; }
  26. DAO  Créer une Classe PersonneDAO  Connection conn=MyConnection.getInstance();  Statement ste;  Méthodes CRUD  public int Ajouter (Personne p)  public Vector<Personne> readAll()  public boolean update (Personne p)  public boolean delete (int id)  public Personne findById (int id)
  27. FindByID public Personne findById(int id){ Personne p = null; try { ste = conn.createStatement(); String req="select * from personne where id="+id; ResultSet rs=ste.executeQuery(req); rs.next(); p=new Personne(rs.getInt(1),rs.getString(2),rs.getString(3)); } catch (SQLException ex) { System.out.println("id n'existe pas"); } return p; }
  28. Test  Instancier une PersonneDAO  PersonneDAO per=new PersonneDAO();  Instancier une Personne  Personne p=new Personne(1,"esprit", "ecole");  Ajouter une personne  Lire toutes les informations des personnes  per.Ajouter(p);  System.out.println(per.readAll());
  29. Void Main public static void main(String[] args) { PersonneDAO per=new PersonneDAO(); Personne p=new Personne(1,"ffghf", "gfghg"); try { per.Ajouter(p); System.out.println(per.readAll()); } catch (SQLException ex) { } }
Publicité