iriszn
Messages postés5Date d'inscriptionlundi 7 juillet 2008StatutMembreDernière intervention24 février 2010
-
23 févr. 2010 à 17:15
tpoinsot
Messages postés345Date d'inscriptionmardi 1 juin 2004StatutMembreDernière intervention17 octobre 2014
-
24 févr. 2010 à 15:49
Voila j'ai un projet pour faire un annuaire téléphonique, l'ajout, la suppression et la création de la table fonctionnent parfaitement. La recherche par nom et ville ne m'affiche qu'un contact (par exemple si j'ai dupont et dupont à paris j'ai que le dernier dupont que j'ai rentré dans la base), pareil pour l'affichage de tous l'annuaire, pour l'affichage par ville ou par lettre Alphabétique. Quelqu'un pourrait-il m'aider pour finir cela?
Je dois aussi faire la modification de contact comment puis-je faire? (la requête je l'ai déjà mais je veux être efficace) HELP!
// JDBCDemo1.java
import java.sql.*;
import java.io.*;
/** Demonstrates the use of JDBC to interact with a database. */
public class JDBCDemo1
{
/** Les pilotes JDBC. */
private static final String DB_DRIVER = "org.gjt.mm.mysql.Driver";
/** L'URL de la base de données. */
private static final String DB_URL = "jdbc:mysql:///projet_java";
/** Retourne une connexion à la base de données. */
public Connection getConnection() throws ClassNotFoundException, SQLException
{
Connection con = null;
Class.forName(DB_DRIVER);
con = DriverManager.getConnection(DB_URL, "root", "");
return con;
}
/** Création de la table de l'annuaire téléphonique. */
public void createTable(Connection con) throws SQLException
{
Statement stmt = null;
String query;
try
{
query = "CREATE TABLE address_book("
+ " id_entree INT NOT NULL AUTO_INCREMENT,"
+ " nom VARCHAR(30),"
+ " prenom VARCHAR(30),"
+ " adresse VARCHAR(50),"
+ " code_postal INT,"
+ " ville VARCHAR(50),"
+ " telephone INT,"
+ " email VARCHAR(50),"
+ " PRIMARY KEY(id_entree))";
stmt = con.createStatement();
stmt.executeUpdate(query);
}
finally
{
// Ferme le Statement
if (stmt != null)
{
stmt.close();
}
}
}
/** Ajoute un contact dans l'annuaire téléphonique. Retourne 1 si le contact est ajouté avec succès. */
public int add(Connection con, String nom, String prenom, String adresse, String ville, String code_postal, String telephone, String email)
throws SQLException
{
// La valeur à retourner
int n = 0;
Statement stmt = null;
String query;
try
{
query = "INSERT INTO address_book(nom, prenom, "
+ "adresse, code_postal, ville, telephone, email)"
+ " VALUES('"
+ nom
+ "', '"
+ prenom
+ "', '"
+ adresse
+ "', '"
+ code_postal
+ "', '"
+ ville
+ "', '"
+ telephone
+ "', '"
+ email
+ "')";
stmt = con.createStatement();
n = stmt.executeUpdate(query);
}
finally
{
// Ferme le Statement
if (stmt != null)
{
stmt.close();
}
}
return n;
}
/** Supprimer les données dans l'annuaire. */
public int supprimer(Connection con, String nom, String prenom, String ville)
throws SQLException
{
// C'est la valeur à retourner
int n = 0;
Statement stmt = null;
String query;
try
{
query = "DELETE FROM address_book "
+ "WHERE nom LIKE '"
+ nom
+ "%' AND prenom LIKE '"
+ prenom
+ "%' AND ville LIKE '"
+ ville
+ "%'";
stmt = con.createStatement();
n = stmt.executeUpdate(query);
}
finally
{
// Ferme le Statement
if (stmt != null)
{
stmt.close();
}
}
return n;
}
/** Recherche un contact dans l'annuaire téléphonique. */
public AddressBookEntry lookup(Connection con, String nom, String ville)
throws SQLException
{
// Valeur à retourner.
AddressBookEntry entry = null;
Statement stmt = null;
ResultSet rs = null;
String query;
//int j;
String id_entree;
String prenom;
String adresse;
String code_postal;
String telephone;
String email;
try
{
query = "SELECT * "
+ "FROM address_book"
+ " WHERE nom LIKE '"
+ nom
+ "%'"
+ " AND ville LIKE '"
+ ville
+ "%'";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
int columns = meta.getColumnCount();
//Array rslt = rs.getArray(nom);
//ResultSet tableau = rslt.getResultSet();
//while(tableau.next()){
//System.out.println(tableau.getObject(1));
// j = 1;
/*if(rs.next())
{*/
// Incrémentation des valeurs*/
/*id_entree = rs.getString(j++);
nom = rs.getString(j++);
prenom = rs.getString(j++);
adresse = rs.getString(j++);
code_postal = rs.getString(j++);
ville = rs.getString(j++);
telephone = rs.getString(j++);
email = rs.getString(j++);*/
while (rs.next())
{
//for(int i=1;i<= 10;i++)
//{
id_entree = rs.getString(meta.getColumnLabel(1));
nom = rs.getString(meta.getColumnLabel(2));
prenom = rs.getString(meta.getColumnLabel(3));
adresse = rs.getString(meta.getColumnLabel(4));
code_postal = rs.getString(meta.getColumnLabel(5));
ville = rs.getString(meta.getColumnLabel(6));
telephone = rs.getString(meta.getColumnLabel(7));
email = rs.getString(meta.getColumnLabel(8));
entry = new AddressBookEntry(nom, prenom, adresse, code_postal, ville, telephone, email);
//}
//System.out.println();
}
// Mise à jour de la valeur retournée
//entry = new AddressBookEntry(nom, prenom, adresse, code_postal, ville, telephone, email);
//}
}
finally
{
// Clean up
try
{
if (rs != null)
{
rs.close();
}
}
catch(Exception ex) {}
try
{
if (stmt != null)
{
stmt.close();
}
}
catch(Exception ex) {}
}
return entry;
}
/** Afficher les contacts dans l'annuaire téléphonique commençant par une lettre. */
public AddressBookEntry rechercheAlpha(Connection con, String nom)
throws SQLException
{
// Valeur à retourner.
AddressBookEntry entry = null;
Statement stmt = null;
ResultSet rs = null;
String query;
String id_entree;
String prenom;
String adresse;
String code_postal;
String ville;
String telephone;
String email;
try
{
query = "SELECT * FROM address_book"
+ " WHERE nom LIKE '"
+ nom
+ "%'"
+ "ORDER BY nom";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
while (rs.next())
{
id_entree = rs.getString(meta.getColumnLabel(1));
nom = rs.getString(meta.getColumnLabel(2));
prenom = rs.getString(meta.getColumnLabel(3));
adresse = rs.getString(meta.getColumnLabel(4));
code_postal = rs.getString(meta.getColumnLabel(5));
ville = rs.getString(meta.getColumnLabel(6));
telephone = rs.getString(meta.getColumnLabel(7));
email = rs.getString(meta.getColumnLabel(8));
entry = new AddressBookEntry(nom, prenom, adresse, code_postal, ville, telephone, email);
}
}
finally
{
// Clean up
try
{
if (rs != null)
{
rs.close();
}
}
catch(Exception ex) {}
try
{
if (stmt != null)
{
stmt.close();
}
}
catch(Exception ex) {}
}
return entry;
}
/** Afficher les contacts dans l'annuaire téléphonique commençant par une lettre. */
public AddressBookEntry rechercheVille(Connection con, String ville)
throws SQLException
{
// Valeur à retourner.
AddressBookEntry entry = null;
Statement stmt = null;
ResultSet rs = null;
String query;
//String id_entree;
String nom;
String prenom;
String adresse;
String code_postal;
String telephone;
String email;
try
{
query = "SELECT * FROM address_book"
+ " WHERE ville LIKE '"
+ ville
+ "%'"
+ " GROUP BY ville"
+ " ORDER BY nom";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
while (rs.next())
{
//id_entree = rs.getString(meta.getColumnLabel(1));
nom = rs.getString(meta.getColumnLabel(2));
prenom = rs.getString(meta.getColumnLabel(3));
adresse = rs.getString(meta.getColumnLabel(4));
code_postal = rs.getString(meta.getColumnLabel(5));
ville = rs.getString(meta.getColumnLabel(6));
telephone = rs.getString(meta.getColumnLabel(7));
email = rs.getString(meta.getColumnLabel(8));
entry = new AddressBookEntry(nom, prenom, adresse, code_postal, ville, telephone, email);
}
}
finally
{
// Clean up
try
{
if (rs != null)
{
rs.close();
}
}
catch(Exception ex) {}
try
{
if (stmt != null)
{
stmt.close();
}
}
catch(Exception ex) {}
}
return entry;
}
/** Main. */
public static void main(String[] args)
{
JDBCDemo1 jdbcDemo = new JDBCDemo1();
Connection con = null;
BufferedReader in;
boolean continueFlag = true;
Statement stmt = null;
ResultSet rs = null;
String choiceStr;
int choice;
String nom;
String prenom;
String adresse;
String ville;
String code_postal;
String telephone;
String email;
String query1;
AddressBookEntry entry;
try
{
// Get a database connection
con = jdbcDemo.getConnection();
query1 = "SELECT TABLE_NAME"
+ " FROM INFORMATION_SCHEMA.TABLES"
+ " WHERE TABLE_NAME like 'adress_book'"
;
stmt = con.createStatement();
rs = stmt.executeQuery(query1);
//parcours des données retournées
try
{
boolean encore = rs.next();
if (!encore)
{
jdbcDemo.createTable(con);
printResult("Table crée avec succès.");
}
rs.close();
}
catch (SQLException e)
{
//traitement de l'exception
}
// Obtain a reader for reading standard input for convenience
in = new BufferedReader(new InputStreamReader(System.in));
while(continueFlag)
{
System.out.println();
System.out.println();
System.out.println(" *** Menu Annuaire Téléphonique ***");
System.out.println();
System.out.println("Choisissez votre option parmi les options 1-5 suivantes :");
//System.out.println("1. Create the addressbook table");
System.out.println("2. Ajouter un contact dans l'annuaire");
System.out.println("3. Rechercher un contact dans l'annuaire");
System.out.println("4. Supprimer un contact dans l'annuaire");
System.out.println("5. Afficher tous les contacts de l'annuaire");
System.out.println("6. Afficher les contacts par lettre alphabétique");
System.out.println("7. Afficher tous les contacts par ville");
System.out.println("8. Quitter");
System.out.print("Entrez votre choix [1-8]: ");
choiceStr = in.readLine();
try
{
// Determine the option
choice = Integer.parseInt(choiceStr);
// Handle option
switch(choice)
{
case 1:
// Create table
//jdbcDemo.createTable(con);
printResult("Table crée avec succès.");
break;
case 2:
// Ajouter un contact
System.out.println("Entrez les informations suivantes.");
System.out.print("Nom: ");
nom = in.readLine();
System.out.print("Prenom: ");
prenom = in.readLine();
System.out.print("Adresse: ");
adresse = in.readLine();
System.out.print("Code Postal: ");
code_postal = in.readLine();
System.out.print("Ville: ");
ville = in.readLine();
System.out.print("Telephone: ");
telephone = in.readLine();
System.out.print("Email: ");
email = in.readLine();
jdbcDemo.add(con, nom, prenom, adresse, ville, code_postal, telephone, email);
printResult("Contact entré avec succès.");
break;
case 3:
// Search an entry
System.out.print("Entrez le nom du contact recherché: ");
nom = in.readLine();
System.out.print("Entrez la ville du contact recherché: ");
ville = in.readLine();
entry = jdbcDemo.lookup(con, nom, ville);
if (entry != null)
{
String entry_conv = entry.getNom()+", "+entry.getPrenom()+", "+entry.getAdresse()+", "+entry.getCodeP()+", "+entry.getVille()+", 0"+entry.getTel()+", "+entry.getEmail();
printResult(entry_conv);
}
else
{
printResult("Aucun contact dans l'annuaire, ayant ce nom dans la ville spécifiée.");
}
break;
case 4:
//Supprimer un contact
System.out.print("Entrez le nom du contact à supprimer: ");
nom = in.readLine();
System.out.print("Entrez le prénom du contact à supprimer: ");
prenom = in.readLine();
System.out.print("Entrez la ville du contact à supprimer: ");
ville = in.readLine();
jdbcDemo.supprimer(con, nom, prenom, ville);
printResult("Contact Supprimé.");
break;
case 5:
// Search an entry
System.out.print("Entrez la 1ère lettre du nom du contact recherché: ");
nom = in.readLine();
entry = jdbcDemo.rechercheAlpha(con, nom);
boolean encore = rs.next();
if (entry != null)
{
while (!encore)
{
String entry_conv = entry.getNom()+", "+entry.getPrenom()+", "+entry.getAdresse()+", "+entry.getCodeP()+", "+entry.getVille()+", 0"+entry.getTel()+", "+entry.getEmail();
printResult(entry_conv);
}
}
else
{
printResult("Aucun contact dans l'annuaire commençant par "+nom);
}
break;
case 6:
// Search an entry
System.out.print("Entrez la ville du contact recherché: ");
ville = in.readLine();
entry = jdbcDemo.rechercheVille(con, ville);
if (entry != null)
{
String entry_conv = entry.getNom()+", "+entry.getPrenom()+", "+entry.getAdresse()+", "+entry.getCodeP()+", "+entry.getVille()+", 0"+entry.getTel()+", "+entry.getEmail();
printResult(entry_conv);
}
else
{
printResult("Aucun contact dans l'annuaire dans la ville suivante:" +ville);
}
break;
case 7:
// Quit
continueFlag = false;
break;
default:
// Choix Incorrect
System.out.println();
System.out.println("Choix Incorrect.");
break;
}
}
catch(NumberFormatException ex)
{
System.out.println();
System.out.println("Choix Incorrect.");
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
// Clean up
try
{
if (con != null)
{
con.close();
}
}
catch(SQLException ex)
{
}
// Si le programme quitte correctement
if (!continueFlag)
{
System.out.println();
System.out.println("Merci d'avoir utilisé cet annuaire téléphonique.");
System.out.println();
}
}
}
/** Affiche le resultat. */
public static void printResult(String msg)
{
System.out.println();
System.out.println("RESULTAT: " + msg);
}
}
Voila mes codes sources si quelqu'un peut m'aider ca serait génial. Merci d'avance
PS. J'utilise Eclipse puis je vais essayer de faire une interface graphique après avec NetBeans si quelqu'un a des conseils à me donner ca serait gentil.
tpoinsot
Messages postés345Date d'inscriptionmardi 1 juin 2004StatutMembreDernière intervention17 octobre 20144 24 févr. 2010 à 08:27
Bonjour,
2 réactions :
- ne fait pas de select *, mais liste les champs dans l'ordre que tu veux, tu éviteras le metadata (à moins que soit volontaire).
- quand tu lis plusieurs enregistrements, retourne une liste ou un tableau de AddressBookEntry, car là tu ne renvoie pas grand chose (le dernier seulement)
iriszn
Messages postés5Date d'inscriptionlundi 7 juillet 2008StatutMembreDernière intervention24 février 2010 24 févr. 2010 à 10:28
Bonjour,
J'ai changé le SELECT * et enlevé le metadata maintenant au lieu d'avoir le dernier contact j'ai le premier
Je ne sais pas comment faire les tableaux ou les listes, peux tu m'aider avec un bout de code ou une modif de mon propre code? Merci beaucoup
tpoinsot
Messages postés345Date d'inscriptionmardi 1 juin 2004StatutMembreDernière intervention17 octobre 20144 24 févr. 2010 à 11:23
Utilise le type ArrayList pour les fonctions de lecture.
ex:
ArrayList p = new ArrayList();
...
while ( rs.next() )
{
// là tu devrais faire des fonctions set
id_entree = rs.getString(1);
nom = rs.getString(2);
prenom = rs.getString(3);
adresse = rs.getString(4);
code_postal = rs.getString(5);
ville = rs.getString(6);
telephone = rs.getString(7);
email = rs.getString(8);
entry = new AddressBookEntry(nom, prenom, adresse, code_postal, ville, telephone, email);
p.Add(entry);
}
...
return p; // donc le tableau de taille variable
Au retour, tu as alors un tableau, dont tu peux connaitre le nombre d'éléments et itérer pour l'affichage ou autre action.
thip
Vous n’avez pas trouvé la réponse que vous recherchez ?
iriszn
Messages postés5Date d'inscriptionlundi 7 juillet 2008StatutMembreDernière intervention24 février 2010 24 févr. 2010 à 14:21
Ok merci mais dans le main comment je fais pour récupérer le "p"?
/** Main. */
public static void main(String[] args)
{
JDBCDemo1 jdbcDemo = new JDBCDemo1();
Connection con = null;
BufferedReader in;
boolean continueFlag = true;
Statement stmt = null;
ResultSet rs = null;
String choiceStr;
int choice;
String nom;
String prenom;
String adresse;
String ville;
String code_postal;
String telephone;
String email;
String query1;
AddressBookEntry entry;
ArrayList entryList;
try
{
// Get a database connection
con = jdbcDemo.getConnection();
query1 = "SELECT TABLE_NAME"
+ " FROM INFORMATION_SCHEMA.TABLES"
+ " WHERE TABLE_NAME like 'adress_book'"
;
stmt = con.createStatement();
rs = stmt.executeQuery(query1);
//parcours des données retournées
try
{
boolean encore = rs.next();
if (!encore)
{
jdbcDemo.createTable(con);
printResult("Table crée avec succès.");
}
rs.close();
}
catch (SQLException e)
{
//traitement de l'exception
}
// Obtain a reader for reading standard input for convenience
in = new BufferedReader(new InputStreamReader(System.in));
while(continueFlag)
{
System.out.println();
System.out.println();
System.out.println(" *** Menu Annuaire Téléphonique ***");
System.out.println();
System.out.println("Choisissez votre option parmi les options 1-5 suivantes :");
//System.out.println("1. Create the addressbook table");
System.out.println("2. Ajouter un contact dans l'annuaire");
System.out.println("3. Rechercher un contact dans l'annuaire");
System.out.println("4. Supprimer un contact dans l'annuaire");
System.out.println("5. Afficher tous les contacts de l'annuaire");
System.out.println("6. Afficher les contacts par lettre alphabétique");
System.out.println("7. Afficher tous les contacts par ville");
System.out.println("8. Quitter");
System.out.print("Entrez votre choix [1-8]: ");
choiceStr = in.readLine();
try
{
// Determine the option
choice = Integer.parseInt(choiceStr);
// Handle option
switch(choice)
{
//cas 1 et cas 2 supprimé volontairement pour alléger
case 3:
// Search an entry
System.out.print("Entrez le nom du contact recherché: ");
nom = in.readLine();
System.out.print("Entrez la ville du contact recherché: ");
ville = in.readLine();
entryList = jdbcDemo.lookup(con, nom, ville);
if (entryList != null)
{
for (int i=0; i<entryList.size(); i++)
{
String entry_conv = ;//???
printResult(entry_conv);
}
}
else
{
printResult("Aucun contact dans l'annuaire, ayant ce nom dans la ville spécifiée.");
}
break;
Comment puis-je faire pour la boucle dans le MAIN? merci
IRIS FRANCE
tpoinsot
Messages postés345Date d'inscriptionmardi 1 juin 2004StatutMembreDernière intervention17 octobre 20144 24 févr. 2010 à 15:10
l'appel à lookup parait nickel :
for (int i=0; i<entryList.size(); i++)
{
AddressBookEntry e = entrylist.get(i);
// comme tu veux
//printResult(...);
}
Souvent on crée des méthode get et set pour chaque propiété. Toi tu fais un new avec toutes les propriétés d'un coup. C'est un choix, qui permet d'avoir un objet non modifiable après création.
iriszn
Messages postés5Date d'inscriptionlundi 7 juillet 2008StatutMembreDernière intervention24 février 2010 24 févr. 2010 à 15:38
Toujours pas ca affiche un contact. Voici ce que j'ai fais. Ok j'ai fais les set.
public void setNom(String nom)
{
this.nom=nom;
}
Comme ca.
Voici toutes mes modif
/** Recherche un contact dans l'annuaire téléphonique. */
public ArrayList lookup(Connection con, String nom, String ville)
throws SQLException
{
// Valeur à retourner.
AddressBookEntry entry = null;
Statement stmt = null;
ResultSet rs = null;
String query;
//int j;
String id_entree;
String prenom;
String adresse;
String code_postal;
String telephone;
String email;
ArrayList p = new ArrayList();
try
{
query = "SELECT id_entree, nom, prenom, adresse, code_postal, ville, telephone, email "
+ "FROM address_book"
+ " WHERE nom LIKE '"
+ nom
+ "%'"
+ " AND ville LIKE '"
+ ville
+ "%'";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
if(rs.next())
{
// Incrémentation des valeurs*/
id_entree = rs.getString(1);
nom = rs.getString(2);
prenom = rs.getString(3);
adresse = rs.getString(4);
code_postal = rs.getString(5);
ville = rs.getString(6);
telephone = rs.getString(7);
email = rs.getString(8);
entry = new AddressBookEntry(nom, prenom, adresse, code_postal, ville, telephone, email);
p.add(entry);
}
}
finally
{
// Clean up
try
{
if (rs != null)
{
rs.close();
}
}
catch(Exception ex) {}
try
{
if (stmt != null)
{
stmt.close();
}
}
catch(Exception ex) {}
}
return p;
}
Et voila mon MAIN de maintenant
/** Main. */
public static void main(String[] args)
{
JDBCDemo1 jdbcDemo = new JDBCDemo1();
Connection con = null;
BufferedReader in;
boolean continueFlag = true;
Statement stmt = null;
ResultSet rs = null;
String choiceStr;
int choice;
String nom;
String prenom;
String adresse;
String ville;
String code_postal;
String telephone;
String email;
String query1;
AddressBookEntry entry;
ArrayList entryList;
try
{
// Get a database connection
con = jdbcDemo.getConnection();
query1 = "SELECT TABLE_NAME"
+ " FROM INFORMATION_SCHEMA.TABLES"
+ " WHERE TABLE_NAME like 'adress_book'"
;
stmt = con.createStatement();
rs = stmt.executeQuery(query1);
//parcours des données retournées
try
{
boolean encore = rs.next();
if (!encore)
{
jdbcDemo.createTable(con);
printResult("Table crée avec succès.");
}
rs.close();
}
catch (SQLException e)
{
//traitement de l'exception
}
// Obtain a reader for reading standard input for convenience
in = new BufferedReader(new InputStreamReader(System.in));
while(continueFlag)
{
System.out.println();
System.out.println();
System.out.println(" *** Menu Annuaire Téléphonique ***");
System.out.println();
System.out.println("Choisissez votre option parmi les options 1-5 suivantes :");
//System.out.println("1. Create the addressbook table");
System.out.println("2. Ajouter un contact dans l'annuaire");
System.out.println("3. Rechercher un contact dans l'annuaire");
System.out.println("4. Supprimer un contact dans l'annuaire");
System.out.println("5. Afficher tous les contacts de l'annuaire");
System.out.println("6. Afficher les contacts par lettre alphabétique");
System.out.println("7. Afficher tous les contacts par ville");
System.out.println("8. Quitter");
System.out.print("Entrez votre choix [1-8]: ");
choiceStr = in.readLine();
try
{
// Determine the option
choice = Integer.parseInt(choiceStr);
// Handle option
switch(choice)
{
case 3:
// Search an entry
System.out.print("Entrez le nom du contact recherché: ");
nom = in.readLine();
System.out.print("Entrez la ville du contact recherché: ");
ville = in.readLine();
entryList = jdbcDemo.lookup(con, nom, ville);
if (entryList != null)
{
for (int i=0; i<entryList.size(); i++)
{
//String entry_conv = entryList.get(i).getNom()+", "+entryList.get(i).getPrenom();
//printResult(entry_conv);
AddressBookEntry e = entryList.get(i);
printResult(e.getNom());
}
}
else
{
printResult("Aucun contact dans l'annuaire, ayant ce nom dans la ville spécifiée.");
}
break;
// les autres cas ne sont pas affichés ici volontairement
/** Affiche le resultat. */
public static void printResult(String msg)
{
System.out.println();
System.out.println("RESULTAT: " + msg);
}
}