IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Requêtes MySQL Discussion :

Probleme ForeignKey et Insert


Sujet :

Requêtes MySQL

Mode arborescent

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2012
    Messages
    277
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Pas de Calais (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 277
    Par défaut Probleme ForeignKey et Insert
    Bonjour,

    j'essai de faire un INSERT INTO, je suis nouveau dans le domaine de la base de donnée et c'est assez confu.

    voici mon message d'erreur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    erreurCannot add or update a child row: a foreign key constraint fails (`base_magasin`.`categorie_article`, CONSTRAINT `fk_categorie_has_article_categorie1` FOREIGN KEY (`categorie_id`) REFERENCES `categorie` (`id_categorie`) ON DELETE NO ACTION ON UPDATE NO ACTIO)
    fr.xxx.dao.DAOException: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`base_magasin`.`categorie_article`, CONSTRAINT `fk_categorie_has_article_categorie1` FOREIGN KEY (`categorie_id`) REFERENCES `categorie` (`id_categorie`) ON DELETE NO ACTION ON UPDATE NO ACTIO)
    	at fr.xxx.dao.ArticleDaoImpl.creer(ArticleDaoImpl.java:61)
    	at fr.xxx.form.ArticleAjoutForm.ajouterArticle(ArticleAjoutForm.java:81)
    	at fr.xxx.servlet.Ajouter_article.doPost(Ajouter_article.java:73)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
    	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    	at java.lang.Thread.run(Unknown Source)
    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`base_magasin`.`categorie_article`, CONSTRAINT `fk_categorie_has_article_categorie1` FOREIGN KEY (`categorie_id`) REFERENCES `categorie` (`id_categorie`) ON DELETE NO ACTION ON UPDATE NO ACTIO)
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    	at java.lang.reflect.Constructor.newInstance(Unknown Source)
    	at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    	at com.mysql.jdbc.Util.getInstance(Util.java:386)
    	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
    	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4187)
    	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4119)
    	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
    	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
    	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
    	at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
    	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
    	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
    	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
    	at fr.xxx.dao.ArticleDaoImpl.creer(ArticleDaoImpl.java:53)
    	... 20 more
    Je vous ai mis un morceau de mon shéma MCD en pièce jointe.

    Et voici un bout de code java concerné :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    private static final String SQL_INSERT = "INSERT INTO article (numero_rma_article, date_achat_brut_article, code_fournisseur_article, code_magasin_article, designation_article, prix_achat_ht_article, numero_serie_article, prix_vente_ttc_article, date_vente_article, prix_vente_ht_article) VALUES (? , ? , ? , ? , ? , ? , ? , ? , ? , ? )";
    	private static final String SQL_INSERT_JOINTURE = "INSERT INTO categorie_article (categorie_id, article_id) VALUES (? , ?)";
    	@Override
    	public void creer(Article article) throws DAOException {
    		// TODO Auto-generated method stub
     
    		Connection connexion = null;
    		PreparedStatement preparedStatement = null;
    		ResultSet valeursAutoGenerees = null;
     
    		try {
    			System.out.println("connection et ajout de l'article");
    			/* Récupération d'une connexion depuis la Factory */
    			connexion = daoFactory.getConnection();
    			System.out.println("contenu article "+article.getNumero_rma_article());
    			preparedStatement = initialisationRequetePreparee( connexion, SQL_INSERT, true, article.getNumero_rma_article(), article.getDate_achat_brut_article(), article.getCode_fournisseur_article(), article.getCode_magasin_article(), article.getDesignation_article(), article.getPrix_achat_ht_article(), article.getNumero_serie_article(), article.getPrix_vente_ttc_article(), article.getDate_vente_article(), article.getPrix_vente_ht_article());
    			int statut = preparedStatement.executeUpdate();
    			System.out.println("valeur statut : "+statut);
    			/* Analyse du statut retourné par la requête d'insertion */
    			if ( statut == 0 ) {
    				throw new DAOException( "Échec de la création de l'article, aucune ligne ajoutée dans la table." );
    			}
    			/* Récupération de l'id auto-généré par la requête d'insertion */
    			valeursAutoGenerees = preparedStatement.getGeneratedKeys();
    			System.out.println("valeursAutoGenerees "+valeursAutoGenerees);
    			if ( valeursAutoGenerees.next() ) {
    				/* Puis initialisation de la propriété id du bean categorie avec sa valeur */
    				article.setId_article( valeursAutoGenerees.getInt(1) );
    				System.out.println("valeur de l'id de l'article ajouter : "+article.getId_article()+" "+article.getCategorie_article());
    				preparedStatement = initialisationRequetePreparee( connexion, SQL_INSERT_JOINTURE, false, article.getId_article(), article.getCategorie_article());
    				int statut2 = preparedStatement.executeUpdate();
    				System.out.println("valeur statut2 : "+statut2);
     
    			} else {
    				throw new DAOException( "Échec de la création de l'article en base, aucun ID auto-généré retourné." );
    			}
    		} catch ( SQLException e ) {
    			System.out.println("erreur"+e.getMessage());
    			throw new DAOException( e );
     
    		} finally {
    			fermeturesSilencieuses( valeursAutoGenerees, preparedStatement, connexion );
    		}
    	}
    En fait le programme rale sur mon second INSERT INTO avec pour requête : SQL_INSERT_JOINTURE

    Le premier Insert passe bien puisque c'est la classe mère d'après ce que j'ai compris.
    Images attachées Images attachées  

Discussions similaires

  1. Probleme de mode insertion / edition
    Par Chimere dans le forum Bases de données
    Réponses: 9
    Dernier message: 02/09/2006, 17h45
  2. [débutant]probleme execution requete INSERT
    Par melodie53 dans le forum JDBC
    Réponses: 2
    Dernier message: 03/08/2006, 16h45
  3. Probleme de requete 'Insert Into'
    Par azerty53 dans le forum Langage SQL
    Réponses: 3
    Dernier message: 12/05/2006, 14h33
  4. probleme dans un INSERT INTO...........SELECT
    Par briiice dans le forum Requêtes
    Réponses: 5
    Dernier message: 26/01/2006, 15h13
  5. Probleme pour les insertion au format etranger
    Par Sandrine75 dans le forum XMLRAD
    Réponses: 5
    Dernier message: 19/03/2003, 10h55

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo