L3 Info : SGBD
 
◃  Ch. 13 JDBC  ▹
 

Exemple complet

String url = "jdbc:postgresql://localhost:5433/dominique"; //5432 port par défaut
Connection connex;
Statement stmt;
String query = "SELECT * FROM auteur WHERE aut_id > 60 ORDER BY aut_nom, aut_prenom";
try {
    Class.forName("org.postgresql.Driver");
} catch(java.lang.ClassNotFoundException e) {
    System.err.print("ClassNotFoundException (try): ");
    System.err.println(e.getMessage());
}

try {
    Properties props = new Properties();
    props.setProperty("user","dom");
    props.setProperty("password","toto");

    connex = DriverManager.getConnection(url,props);
    stmt = connex.createStatement();

    ResultSet rs = stmt.executeQuery(query);
    System.out.println("Quelques auteurs :");

    while (rs.next()) {
        int id = rs.getInt("aut_id");
        String nom = rs.getString("aut_nom");
        String prenom = rs.getString("aut_prenom");
        System.out.println(id + " " + nom+ " " + prenom );
    }
    rs.close();
    stmt.close();
    connex.close();
} catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
}