【问题标题】:Code not detecting empty input from user代码未检测到用户的空输入
【发布时间】:2017-11-25 13:38:08
【问题描述】:

我对删除按钮有疑问。当我在文本字段中不输入任何内容并按下删除按钮时,我没有得到一个弹出菜单作为例外。

 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
}

【问题讨论】:

  • 看起来你也应该收到 java.lang.NumberFormatException 以防 Integer.parseInt 收到它不理解的输入。
  • billidtext.getText().trim().isEmpty()

标签: java exception jdbc sqlexception


【解决方案1】:
if (!billidtext.getText().trim().isEmpty()) {
    // Do query
}

如前所述,您需要明确地将java.lang.NumberFormatException 捕获为int 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    相关资源
    最近更新 更多