Partage
  • Partager sur Facebook
  • Partager sur Twitter

Problème d'utilisation de Derby

    17 avril 2012 à 1:28:45

    Bonsoir à tous,

    J'ai fais une classe pour "manager" ma base de données Derby. Mais voilà, quand vient même le temps de tester le code, les résultats ne sont pas vraiment ceux attendus. En gros, dans le main(), pour tester, je tente de créer une nouvelle table puis de voir si celle-ci a bien été créée (fonction tableExists) et donc apparemment la table n'a pas été créée. Pourriez-vous me dire ce qui ne va pas dans ma classe DatabaseManager svp?

    package org.debatz.schoolManager;
    
    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.List;
    import java.util.Properties;
    import com.sun.tools.javac.util.Pair;
    
    
    public class DatabaseManager {
    	
    	private final static String dbUser = "user1";
    	private final static String dbName = "derbyDB";
    	private final static String dbPassword = "user1";
    	
    	private final static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
    	private final static String protocol = "jdbc:derby:";
    	
    	public final static String COURSES_TABLE = "COURSES";
    	
    	private static Connection connect;
    	    
    
    
    	    public DatabaseManager () throws SQLException {
    	    	Properties properties = new Properties();
    	    	properties.put("user", dbUser); // schema
    	    	properties.put("password", dbPassword);
                    connect = DriverManager.getConnection(protocol + dbName + ";created=true", properties);
                    connect.setAutoCommit(false);
                    System.out.println("Nous voilà connecté à la base " + dbName);
                    System.out.println("connect = " + connect); // on affiche ce que contient la variable de connexion
                    loadDriver(); // on charge les drivers
    	    }
    	    
    	    
    	    public boolean tableExists (String tableName) throws Exception {
    	         ResultSet rs;
    	         boolean exists;
    	         
    	         try {
    	             DatabaseMetaData md = connect.getMetaData();
    	             rs = md.getTables(null, dbName, tableName, null);
    	             exists = rs.next();
    	         } finally {
    	        	 closeConnection();
    	         }
    	         return exists;
    	    } 
    
    	    public boolean createTable (String tableName, List<Pair<String, String>> fields) throws Exception {
    	    	Statement s = null;
    	    	if (!tableExists(tableName)) {
    	    		String query = "CREATE TABLE " + tableName + "(";
    	    		s = connect.createStatement();
    	    		for (int i = 0; i < fields.size(); i++)
    	    			query += (i == 0) ? fields.get(i).fst + " " + fields.get(i).snd : ", " + fields.get(i).fst + " " + fields.get(i).snd;
    	    		query += ")";
    	    		System.out.println(query);
    	    		return s.execute(query); // renvoi false ici.. pourquoi?
    	    	}
    	    	return false;
    	    }
    
    private static void closeConnection () {
    	    	if (connect == null) {
    	    		try {
    	    			connect.close();
    	    			DriverManager.getConnection("jdbc:derby:" + dbName + ";shutdown=true");
    	    		}
                    catch (SQLException se)
                    {
                        if (se.getErrorCode() == 50000 && ("XJ015").equals(se.getSQLState())) {
                            System.out.println("Derby shut down normally");
                        } else {
                            System.err.println("Derby did not shut down normally");
                            printSQLException(se);
                        }
                    }
    	    	}
    	    }
    	  
    
    	    private static void loadDriver() {
    	      
    	        try {
    	            Class.forName(driver).newInstance();
    	            System.out.println("Loaded the appropriate driver");
    	        } catch (ClassNotFoundException cnfe) {
    	            System.err.println("\nUnable to load the JDBC driver " + driver);
    	            System.err.println("Please check your CLASSPATH.");
    	            cnfe.printStackTrace(System.err);
    	        } catch (InstantiationException ie) {
    	            System.err.println("\nUnable to instantiate the JDBC driver " + driver);
    	            ie.printStackTrace(System.err);
    	        } catch (IllegalAccessException iae) {
    	            System.err.println("\nNot allowed to access the JDBC driver " + driver);
    	            iae.printStackTrace(System.err);
    	        }
    	    }
    
    
    	    public static void printSQLException(SQLException e)
    	    {
    	        while (e != null)
    	        {
    	            System.err.println("\n----- SQLException -----");
    	            System.err.println("  SQL State:  " + e.getSQLState());
    	            System.err.println("  Error Code: " + e.getErrorCode());
    
    	            e = e.getNextException();
    	        }
    	    }
    	    
    	}
    



    et voici le main de test :

    package org.debatz.schoolManager;
    
    
    import java.util.ArrayList;
    import java.util.List;
    import com.sun.tools.javac.util.Pair;
    
    
    public class SchoolManager {
    	    
    
    	public static void main(String[] args) {
    		try {
    			DatabaseManager dbm = new DatabaseManager();
    			
    			List<Pair<String, String>> fields = new ArrayList<Pair<String, String>>();
    			fields.add(new Pair<String, String>("course_id", "INT PRIMARY KEY generated always AS identity (start WITH 0, increment BY 1)"));
    			fields.add(new Pair<String, String>("course_name", "CHAR(50)"));
    			fields.add(new Pair<String, String>("course_option", "SMALLINT"));
    			
    			System.out.println(
    					dbm.createTable(DatabaseManager.COURSES_TABLE, fields)
    				);
    			
    			System.out.println(
    					dbm.tableExists(DatabaseManager.COURSES_TABLE)
    				);
    		
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    



    Voici ce que cela m'affiche lors de l'exécution :

    Citation

    Nous voilà connecté à la base derbyDB
    connect = org.apache.derby.impl.jdbc.EmbedConnection40@1826959904 (XID = 588), (SESSIONID = 1), (DATABASE = derbyDB), (DRDAID = null)
    Loaded the appropriate driver
    CREATE TABLE COURSES(course_id INT PRIMARY KEY generated always AS identity (start WITH 0, increment BY 1), course_name CHAR(50), course_option SMALLINT)
    false
    false



    On voit clairement (je pense) que c'est la fonction s.execute(query) dans la méthode "createTable" qui ne fonctionne pas puisqu'elle renvoit false alors que la requête SQL elle, a l'air plutôt bonne non? Qu'en pensez-vous?

    Merci de votre aide.
    Le truc c'est que la base doit fonctionner normalement vu que j'avais chopé la source de base sur un site et les tests fonctionnaient. Cela dit, l'auteur avait tout mis dans le main. C'est donc le fait que j'ai mis le code dans une classe qui a un peu mis le bazare.
    • Partager sur Facebook
    • Partager sur Twitter

    Problème d'utilisation de Derby

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown