0

Trying to insert an entry into a database by a radio button Option throws me this Exception I tried to get answer by the similar questions but i did not get one.

The code is as follows :

private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
   jPanel2.setVisible(true);
    try{
      Class.forName("com.mysql.jdbc.Driver");
      String url="jdbc:mysql://localhost:3306/test";
      Connection conn=DriverManager.getConnection(url,"root","Sumit");
      String query="Insert student values(?,?,?)";
      PreparedStatement pst=conn.prepareStatement(query);
      pst.setString(1, jTextField1.getText());
      pst.setString(2, jTextField2.getText());
      pst.setInt(3, Integer.parseInt(jTextField3.getText()));
      int rec=pst.executeUpdate();
      if(rec>0)
      {
          jLabel6.setText("New Student Added");
          jTextField1.setText(" ");
         jTextField2.setText(" ");
          jTextField3.setText(" ");
      }
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}

Any help would be greatly appreciated. After examining stack trace I found The error is on line no 194 where I parse an Integer from jTextField3.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Sumit Dhiman
  • 109
  • 3
  • 8

1 Answers1

2

jTextField3 does not contain any text that can be parsed into a number, either it contains a string that consists of non-digits or it is empty. Therefore pst.setInt(3, Integer.parseInt(jTextField3.getText())); throws a NumberFormatException when trying to convert the text in the textfield into an integer. For full description of parseInt you can check the API.

The NumberFormatException contains a message which tells you what the input string looked like, for instance java.lang.NumberFormatException: For input string: "xyz"

Pphoenix
  • 1,423
  • 1
  • 15
  • 37
  • 1
    Also, the NumberformatException should provide information on what is wrong, e.g.: Exception in thread "main" java.lang.NumberFormatException: For input string: " " – Christian Kullmann Jul 11 '14 at 11:44
  • Pphoenix I want to enter the values through the text Field.How can i set jtextfield before? the input string is "" – Sumit Dhiman Jul 11 '14 at 11:56
  • @SumitDhiman Easiest way (skipping StringBuilder) int defaultValue = 5; jTextField3.setText(""+defaultValue); // Now textfield contains the number 5 – Pphoenix Jul 11 '14 at 12:00