JAVA / MySql Problème affichage SELECT

Fermé
JayM94 Messages postés 2 Date d'inscription vendredi 19 février 2010 Statut Membre Dernière intervention 21 février 2010 - 20 févr. 2010 à 00:13
JayM94 Messages postés 2 Date d'inscription vendredi 19 février 2010 Statut Membre Dernière intervention 21 février 2010 - 21 févr. 2010 à 20:12
Bonjour,

Voila je dois faire un annuaire téléphonique c'est un projet en JAVA à faire. J'ai pas encore fais la partie graphique car je ne connais rien à cela. Je me suis focalisé sur la partie requête. L'ajout et la supression fonctionnent parfaitement mais le SELECT a un problème au niveau de l'affichage, j'ai un truc comme ceci: "RESULT: AddressBookEntry@d6c16c"

Voila le code avant le main:
/** 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();
		                //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<=columns;i++)
					{
					//System.out.print(rs.getString(i) + " ");
					//System.out.println(rs.getStrin(meta.getColumnLabel(i)));
					id_entree = rs.getString(meta.getColumnLabel(i))+" ";
					nom = rs.getString(meta.getColumnLabel(i))+" ";
					prenom = rs.getString(meta.getColumnLabel(i))+" ";
					adresse = rs.getString(meta.getColumnLabel(i))+" ";
					code_postal = rs.getString(meta.getColumnLabel(i))+" ";
					ville = rs.getString(meta.getColumnLabel(i))+" ";
					telephone = rs.getString(meta.getColumnLabel(i))+" ";
					email = rs.getString(meta.getColumnLabel(i))+" ";
					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;

	}


Et le main :

/** 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 {

// Connexion à la BDD
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 created successfully.");
  	}
   
   	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(" *** Address Book Menu ***");
System.out.println();
System.out.println("Choose your option from 1-4 below");
//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. Quitter");
System.out.print("Entrez votre choix [2-5]: ");
choiceStr = in.readLine();

try {

// Determiner les options
choice = Integer.parseInt(choiceStr);

// Gérer les options
switch(choice) {

case 3:
// Rechercher un contact
System.out.print("Entrez le nom: ");
nom = in.readLine();
System.out.print("Entrez la ville: ");
ville = in.readLine();
entry = jdbcDemo.lookup(con, nom, ville);
if (entry != null) {
	String entry_conv = entry.toString();
printResult(entry_conv);
}
else {
printResult("Aucun contact de ce nom.");
}
break;

case 5:
// Quitter
continueFlag = false;
break;


	

default:
// Choix
System.out.println();
System.out.println("Choix Non Valide.");
break;

}

}
catch(NumberFormatException ex) {
System.out.println();
System.out.println("Invalid choice.");
}

}

}
catch(Exception ex) {
ex.printStackTrace();
}
finally {

// Clean up
try {
if (con != null) {
con.close();
}
}
catch(SQLException ex) {
}

// Si le programme a quitté correctement
if (!continueFlag) {
System.out.println();
System.out.println("Thank you for using the addressbook.");
System.out.println();
}

}

}

/** Affiche les résultat. */
public static void printResult(String msg) {
System.out.println();
System.out.println("RESULT: " + msg);
}

}


J'ai volontairement retiré les autres cases sinon ca fait trop de code.

Ma question est la suivante: comment puis-je faire pour afficher le résultat du SELECT et comment puis-je faire une option pour modifer un contact (avec le UPDATE je sais mais comment?) ? Merci d'avance
A voir également:

2 réponses

Eleth Messages postés 128 Date d'inscription jeudi 15 janvier 2009 Statut Membre Dernière intervention 26 février 2010 17
20 févr. 2010 à 06:20
Salut,

Ta fonction SELECT est à première vue bonne, je pense que ton problème viens seulement de :
case 3:
// Rechercher un contact
System.out.print("Entrez le nom: ");
nom = in.readLine();
System.out.print("Entrez la ville: ");
ville = in.readLine();
entry = jdbcDemo.lookup(con, nom, ville);
if (entry != null) {
	String entry_conv = entry.toString();
printResult(entry_conv);
}
else {
printResult("Aucun contact de ce nom.");
}
break;


Tu transforme un objet en String avec toString(). Et je pense que tu n'as pas override la fonction toString() de ton objet du coup java exécute le toString() de la super classe Object qui retourne un String l'emplacement mémoire de l'objet.

Mais plutôt que d'override une fonction je te suggère d'ajouter une fonction à ta classe AddressBookEntry (si elle n'est pas déjà faite) de ce type :
public String getEntry () {
        String entry = nom+", "+prenom+", "+adresse+", "+code_postal+", "+ville+", "+telephone+", "+email;
        //A toi de voir pour la mise en forme, là j'ai fais le minimum =)
        return entry;
    }


Ensuite tu remplace la ligne :
String entry_conv = entry.toString();

par :
String entry_conv = entry.getEntry();


Après libre à toi de faire ca en plusieurs méthodes pour ne récupérer qu'un éléments de la fiche si tu en as l'utilité (ou si tu en auras l'utilité). Ce qui donnerai :
public String getNom () {
        String monNom = nom;
        return monNom;
    }
...
...
...
public String getEmail () {
        String monEmail = email;
        return monEmail;
    }


Avec :
String entry_conv = entry.getNom()+ ... ... ... +entry.getEmail();


/!\ /!\ /!\
Par contre je suis partis du principe que les variables de ta classe AddressBookEntry étaient toutes de type String, si certaines ont un type différent tu devras les transformer en String à l'intérieur des méthodes getXxx(){...} de ta classe.
/!\ /!\ /!\
0
JayM94 Messages postés 2 Date d'inscription vendredi 19 février 2010 Statut Membre Dernière intervention 21 février 2010
21 févr. 2010 à 20:12
Merci pour ta réponse. J'ai fais comme tu m'as dis en prenant la 2ème solution.

Dans Eclipse:

public String getNom() 
{
        String monNom = nom;
        return monNom;
}


Il me souligne nom et les autres aussi (prenom, email,...)
Et pour la partie MAIN, Eclipse souligne tout après le getNom, comme getPrenom je comprends pas.
if (entry != null) 
{
	String entry_conv = entry.getNom()+entry.getPrenom();
	printResult(entry_conv);
}

Peut-tu me dire comment faire? Merci beaucoup en tout cas
0