问题,没有显示有关空白字段的消息。立即帮助
private void addbtnActionPerformed(java.awt.event.ActionEvent evt){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/dbfinance","root","1234");
String sql="insert into util(type_,due_date,month_,amount,units,status_) values(?,?,?,?,?,?)";
PreparedStatement pstm =con.prepareStatement(sql);
pstm.setString(1,electype.getSelectedItem().toString());
pstm.setString(2,date.getText().toString());
pstm.setString(3,jComboBox1.getSelectedItem().toString());
pstm.setDouble(4,Double.parseDouble(amount.getText()));
pstm.setString(5,unit.getText());
pstm.setString(6,status.getText());
pstm.executeUpdate();
JOptionPane.showMessageDialog(null, "success");
con.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
if(amount.getText().isEmpty()||unit.getText().isEmpty()||status.getText().isEmpty()){
JOptionPane.showMessageDialog(null,"please enter data");
// errorname2.setText("fill this field");
}
}
答案 0 :(得分:1)
在应用try-catch
语句之前,请尝试验证您的金额字段是否为空:
if(amount.getText().isEmpty()||unit.getText().isEmpty()||status.getText().isEmpty()){
JOptionPane.showMessageDialog(null,"please enter data");
// errorname2.setText("fill this field");
}else{
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/dbfinance","root","1234");
String sql="insert into util(type_,due_date,month_,amount,units,status_) values(?,?,?,?,?,?)";
PreparedStatement pstm =con.prepareStatement(sql);
pstm.setString(1,electype.getSelectedItem().toString());
pstm.setString(2,date.getText().toString());
pstm.setString(3,jComboBox1.getSelectedItem().toString());
pstm.setDouble(4,Double.parseDouble(amount.getText()));
pstm.setString(5,unit.getText());
pstm.setString(6,status.getText());
pstm.executeUpdate();
JOptionPane.showMessageDialog(null, "success");
con.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
答案 1 :(得分:1)
在验证之前,您不应该将数据插入数据库中。如果数据不为空,则仅插入数据。至于检查数据是否为空,最好对文本进行修剪,以便给定空白表示某些值,从而将所有空白都修剪掉。
if(amount.getText().trim().isEmpty()||unit.getText().trim().isEmpty()||
status.getText().trim().isEmpty()){
JOptionPane.showMessageDialog(null,"please enter data");
// errorname2.setText("fill this field");
}
请确保将修剪后的数据插入数据库中。