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 52 53 54 55 56 57 58 59 60
|
import java.sql.*;
import java.io.*;
public class CBaseDonnees {
public static void main(String args[]) {
String URL = "jdbc:mysql://localhost:81/ouvrage";
String nomdutilisateur ="moi";
String motdepasse ="meme";
//chargement du pilote
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e) {
System.err.println("le pilote n'est pas chargé");
return;
}
//connexion à la base de données
Statement commande = null;
Connection connexion = null;
try {
connexion = DriverManager.getConnection(
URL,
nomdutilisateur,
motdepasse);
commande = connexion.createStatement();
}
catch(Exception e) {
System.err.println("La connexion " + URL + "ne peut pas être établie");
}
// lecture des données
try {
ResultSet entites;
entites = commande.executeQuery("SELECT * FROM exemple;");
// affichage des entetes
Console cons = System.console();
cons.printf("\n");
cons.printf("nom \t prenom \n");
cons.printf("\n");
// afichage de chaque entite
String nom;
String prenom;
while(entites.next())
{
nom = entites.getString("nom");
prenom = entites.getString("prenom");
cons.printf(" %s \t\t %s \n", nom, prenom);
}
connexion.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
} |
Partager