2017-08-28 1 views
0

Je tente d'enregistrer un champ de mon formulaire jFrame, mais lorsque je clique sur le bouton Enregistrer, j'obtiens l'exception null pointeur. Auparavant j'obtenais les erreurs que le champ de texte ne pouvait pas être nul, donc je ne l'ai pas coché, j'ai décidé de ne pas inclure le Voucher_no dans l'instruction d'insertion MySQL car c'est un incrément automatique et son champ de texte n'est pas modifiable Y a-t-il un problème avec mon code? A l'aide de Mysql Workbench.Champs jFrame ne pas enregistrer à db

try { 
      Class.forName("com.mysql.jdbc.Driver").newInstance(); 
      Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/canning?zeroDateTimeBehavior=convertToNull", "root", ""); 
      con.setAutoCommit(false); 
      try { 

//   String kb = jTextField3.getText(); //voucher_no 
       String kc = (String) jComboBox3.getSelectedItem(); //factory 
       String kg = jTextField10.getText(); //fuel 
       Double ks = Double.valueOf(kg); 
       String ke = jTextField11.getText(); //electricity 
       Double kt = Double.valueOf(ke); 
       String kf = jTextField12.getText(); //manpower 
       Double ku = Double.valueOf(kf); 
       String kj = (String) jComboBox4.getSelectedItem(); //can_name 
       String kk = (String) jComboBox5.getSelectedItem(); //label name 
       String kq = jTextField23.getText();//no_of_cans 
       Double kv = Double.valueOf(kq); 
       String kr = jTextField24.getText();//no_of_labels 
       Double kw = Double.valueOf(kr); 

       String query1= "insert into production (date,factory,fuel,electricity,manpower,can_name,label_name,no_of_cans,no_of_labels)" 
         + "values (?,?,?,?,?,?,?,?,?)"; 

       try (PreparedStatement pst = con.prepareStatement(query1)){ 
//     pst.setString(10, kb); 
        pst.setString(1, ((JTextField) jDate1.getDateEditor().getUiComponent()).getText()); 
        pst.setString(2, kc); 
        pst.setDouble(3, ks); 
        pst.setDouble(4, kt); 
        pst.setDouble(5, ku); 
        pst.setString(6, kj); 
        pst.setString(7, kk); 
        pst.setDouble(8, kv); 
        pst.setDouble(9, kw); 

        pst.execute(); 
       } 


      try { 
         int rows = jTable2.getRowCount(); 

         for (int row = 0; row < rows; row++) { 
          String kd = (String) jTable2.getValueAt(row, 0); 
          Double kn = (Double) jTable2.getValueAt(row, 1); 
          try { 
//      Class.forName("com.mysql.jdbc.Driver").newInstance(); 
//    Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/canning?zeroDateTimeBehavior=convertToNull", "root", ""); 

           String query = "insert into production(product_name,product_quantity)" 
             + "values (?,?)"; 
           PreparedStatement update = con.prepareStatement(query); 
           update.setString(1, kd); 
           update.setDouble(2, kn); 

           update.addBatch(); 

           update.executeBatch(); 
           con.commit(); 

          } catch (SQLException e) { 
           e.printStackTrace(); 
//      JOptionPane.showMessageDialog(this, "Error in production Table"); 
          } 
         } 
        } catch (Exception e) { 
         JOptionPane.showMessageDialog(this, "Invalid Entry in fields"); 
        } 

      } catch (Exception e) { 
       e.printStackTrace(); 
//    JOptionPane.showMessageDialog(null, "Invalid in fields"); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
+0

Avez-vous essayé d'exécuter votre code avec un débogueur afin de savoir quel objet est nul? En outre, essayez d'utiliser des noms de variables explicites, dans l'état actuel, votre code n'est pas lisible du tout .. – SebVb

+0

J'ai utilisé un débogueur et cela indique que le problème est dans ma boucle for pour le jtable mais je ne vois aucun erreur, est là? – Stevoski

Répondre

0

Le code fait

      update.addBatch(); 

          update.executeBatch(); 
          con.commit(); 

executeBatch et commit doit se faire en dehors de la boucle. Le malentendu provient de "addBatch" qui aurait dû être nommé "addToBatch".

+0

J'ai essayé de changer le code mais maintenant j'obtiens l'exception 'nom_produit ne peut pas être nul'} update.executeBatch(); con.commit(); } catch (Exception e) { JOptionPane.showMessageDialog (null, "Impossible d'enregistrer." + E); } – Stevoski

+0

En passant, dans les deux cas, il y a la même table 'production'! Et les deux instructions devraient être exécutées isolées, ou la première avec addBatch aussi. –

+0

Evidemment, kd est nul –

0

Essayez de le faire de cette façon. Commencez par créer une classe de connexion comme suit.

import java.sql.Connection; 
import java.sql.DriverManager; 

public class db_connection 
{ 
    public Connection connection() 
    throws Exception 
    { 
    try 
    { 
     Connection conn = null; 

     String username = "root"; String password = ""; 
     String driver = "com.mysql.jdbc.Driver"; 
     String url = "jdbc:mysql://localhost:3306/database"; 
     try { 
     Class.forName(driver); 
     } catch (Exception e) { 
     e.printStackTrace(); 
     return null; 
    } 

     conn = DriverManager.getConnection(url, username, password); 

     conn.setAutoCommit(false); 
     return conn; 
    } catch (Exception e) { 
     e.printStackTrace(); 
     System.exit(0); 
    }return null; 
    } 
} 

ensuite sur votre bouton Enregistrer ce faire quelque chose comme,

private void ButtonRegGroup_SubmitActionPerformed(java.awt.event.ActionEvent evt) {              
// TODO add your handling code here: 
    if ((this.jTextFieldGrp_ReqAmnt.getText().equals("")) 
      || (this.jTextFieldGrp_name.getText().equals("")) 
      || (this.jTextFieldGrp_Id.getText().equals("")) 
      || (this.jTextFieldGrp_prj_name.getText().equals(""))) { 
     JOptionPane.showMessageDialog(this, "Some fields are empty", this.title, this.error); 
    } else { 
     try { 
      this.con = ((Connection) new db_connection().connection()); 
      this.pst = ((PreparedStatement) this.con.prepareStatement("insert into registered_projects(project_type,name,project_name,project_id,constituency,ward,requested_amount)values(?,?,?,?,?,?,?)")); 

      GroupRegDetails(); 
      this.pst.setString(1, this.proj_type); 
      this.pst.setString(2, this.group_name); 
      this.pst.setString(3, this.proj_name); 
      this.pst.setInt(4, this.proj_id); 
      this.pst.setString(5, this.constituency); 
      this.pst.setString(6, this.ward); 
      this.pst.setInt(7, this.requested_amount); 
      int row = this.pst.executeUpdate(); 
      con.commit(); 
      if (row == 0) { 
       this.con.rollback(); 
       JOptionPane.showInternalMessageDialog(this, "Didn't Register project", this.title, this.error); 
      } 
      JOptionPane.showMessageDialog(this, "Project Successfully Registered", this.title, this.infor); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
public void GroupRegDetails() { 
    this.group_name = this.jTextFieldGrp_name.getText(); 
    this.proj_id = Integer.parseInt(this.jTextFieldGrp_Id.getText()); 
    this.proj_name = this.jTextFieldGrp_prj_name.getText(); 
    this.constituency = this.jComboBoxGrp_Comb_const.getSelectedItem().toString(); 
    this.ward = this.jComboBoxGrp_comb_Ward.getSelectedItem().toString(); 
    this.requested_amount = Integer.parseInt(this.jTextFieldGrp_ReqAmnt.getText()); 
    this.proj_type = "Group"; 
} 

Enfin une bonne pratique est de mettre sur un champs JPanel et JPanel sur un Jframe. J'espère que cela t'aides.

+0

définissez-vous une variable en utilisant 'this.group_name = this.jTextFieldGrp_name.getText();' – Stevoski

+0

Oui, par exemple jTextFieldGrp_name est le nom de la variable de champ. J'ai une variable non initialisée String nom_groupe; et le je lui donne une valeur du champ comme this.group_name = this.jTextFieldGrp_name.getText() ;. J'espère être clair – Simiyu

+0

ouais je vous obtenez, et si vous voulez enregistrer plusieurs lignes de données d'un jtable à une seule ligne dans une base de données MySQL, ie j'ai une production et raw_material jtable où une production contient beaucoup de matières premières. Comment puis-je fais ceci. Je veux qu'ils partagent le même ID de production. – Stevoski