1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
import java.sql.*;
public class Connexion {
public Connexion(){
try {
//Chargement du pilote JDBC
Class.forName("org.postgresql.Driver");
//URL de connexion
String url="jdbc:postgresql://localhost:5432/base";
String login = "postgres";
String password = "mon_password";
//Connexion
Connection con = DriverManager.getConnection(url,login,password);
//creation d'une instruction
Statement sta = con.createStatement();
//execution d'une requete
String query = "SELECT * FROM film"; //exemple de requete
ResultSet leresultat = sta.executeQuery(query);
//Traitement des resultats
while (leresultat.next()) {
System.out.println(leresultat.getString(1)+"\t"+leresultat.getString(2)+"\t"+leresultat.getString(3));
}
//fermeture connexion
con.close();
}
//gestion des erreures probables
catch (SQLException sqle) {
System.err.println("Erreur SQL:"+sqle);
}
catch(ClassNotFoundException cnfe){
System.out.println("Driver introuvable : ");
cnfe.printStackTrace();
}
catch(Exception e){
System.out.println("Autre erreur : ");
e.printStackTrace();
}
}
//methode principale
public static void main (String args[]){
Connexion test = new Connexion();
}
} |
Partager