j'ai deux tables: �tudiant et photo, la relation entre elles est de type fils-fils, alors j'ai la fonction d'insertion de la photo qui retourne la cl� que je re�ois dans la fonction d'insertion de l'�tudiant (en param�tre), la cl� de l'�tudiant est lu depuis un texteField, alors il refuse de l'ins�rer"Cannot add or update a child row: a foreign key constraint fails (`brs`.`photo`, CONSTRAINT `FK_Photo_bac` FOREIGN KEY (`bac`) REFERENCES `etudiant` (`bac`))"
m�thode d'insertion photo:
m�thode d'insertion �tudiant:
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 public int insertPhoto() throws Exception { String query = "INSERT INTO photo (image,bac)" + "VALUES (?,?)"; try (PreparedStatement stat = cnx.prepareStatement(query)) { // code_photo AUTO INCREMENT stat.setBinaryStream(1, fis); // la photo stat.setString(2, txtBAC.getText()); //la clé étrangère depuis un JtextField stat.executeUpdate(); stat.close(); } String codeQuery = "SELECT MAX(code_photo) FROM photo"; try (PreparedStatement stat = cnx.prepareStatement(codeQuery)) { ResultSet rslt = stat.executeQuery(); rslt.next(); return rslt.getInt(1); } }
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 public void insertEtudiant(int codeLieu, int codeNat, String codeF, int codeMotif , int codePhoto) throws Exception { try { String etudiant = "INSERT INTO etudiant (bac,nom,prenom,genre,adresse,n_phone,mail,n_ccp,decision,bloque," + "n_ins,annee_encours,annee_univ,annee_courante,reste," + "an_1,an_2,an_3,an_4,an_5,an_6,an_7,an_8,an_9,an_10," + "cycle,code_f,date_nais,code,code_nat,Observation,date_bloc,code_motif) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; stat = cnx.prepareStatement(etudiant); stat.setString(1, txtBAC.getText()); stat.setString(2, txtNom.getText()); stat.setString(3, txtPrenom.getText()); // // // stat.setInt(31, codePhoto); // // // stat.executeUpdate(); } finally { stat.close(); } }
code d'appel:
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 JButton btnSave = new JButton("Sauvegarder"); btnSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { cnx.setAutoCommit(false); insertPhoto(); // // int codePhoto = insertPhoto(); insertEtudiant(codeLieu, codeNat, codeF, codeMotif , codePhoto); // // cnx.commit(); } catch (Exception e2) { try { cnx.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e2.printStackTrace(); } finally { try { cnx.setAutoCommit(true); } catch (SQLException e1) { e1.printStackTrace(); } } } });
Partager