2017-11-25 69 views
0

我有刪除按鈕的問題。當我在文本字段中輸入任何內容並按下刪除按鈕時,我沒有收到彈出式菜單作爲例外。代碼沒有檢測到來自用戶的空輸入

private void billdeleteActionPerformed(java.awt.event.ActionEvent evt) { 
    // TODO add your handling code here: 
    try{ 
     Class.forName("oracle.jdbc.driver.OracleDriver"); 
     int id=Integer.parseInt(billidtext.getText()); 
     try (//step2 create the connection object 
      Connection con = DriverManager.getConnection("jdbc:oracle:thin:localhost:xe","hr","****")) { 
      Statement stmt=con.createStatement(); 
      stmt = con.createStatement(); 
      String sql = "DELETE FROM bill " + 
      "WHERE bid = ('"+id+"')"; 
      int w=stmt.executeUpdate(sql); 
      if(w!=0) 
      JOptionPane.showMessageDialog(null,"Deleted Successfully!"); //this is displayed successfully 
      else 
      JOptionPane.showMessageDialog(null,"value does not exists!");// this is displayed successfully 
      supplieridtext.setText(""); 

      //view trigger 
      String sql1="SELECT * FROM bill"; 

      stmt = con.createStatement(); 

      ResultSet rs = stmt.executeQuery(sql1); 
      //STEP 5: Extract data from result set 
      billtable.setModel(DbUtils.resultSetToTableModel(rs)); 
      rs.close(); 

      //step5 close the connection object 
     } 
    }catch(ClassNotFoundException | SQLException e){ 
     JOptionPane.showMessageDialog(null,"no value entered!");} //this line is not displayed when the text field is empty 
} 
+0

它看起來像你應該捕獲一個'java.lang.NumberFormatException',以防給'Integer.parseInt'提供一個它不理解的輸入。 –

+0

'billidtext.getText()。trim()。isEmpty()' – MadProgrammer

回答

2
if (!billidtext.getText().trim().isEmpty()) { 
    // Do query 
} 

如前所述,你需要捕獲java.lang.NumberFormatExceptionint id=Integer.parseInt(billidtext.getText());明確,因爲這是一個「未經檢查的異常」

if (!billidtext.getText().trim().isEmpty()) { 
    try { 
     int id=Integer.parseInt(billidtext.getText(); 
     // Do query 
    } catch (java.lang.NumberFormatException exp) { 
     JOptionPane.showMessageDialog(null,"Invalid value!"); 
    } 
} else { 
    JOptionPane.showMessageDialog(null,"no value entered!"); 
} 

你也應該利用的PreparedStatements

相關問題