int p =JOptionPane.showConfirmDialog(null,"Are you sure to add this staff?","Comfirmation",JOptionPane.YES_NO_OPTION);
if (p==0){
String sql ="Insert into login.createstaff (Staff_ID,Staff_Name,Staff_password,Staff_Tel,Staff_position,image) values (?,?,?,?,?,?)";
try {
pst=conn.prepareStatement (sql);
pst.setString(1,staffID.getText());
pst.setString(2,staffName.getText());
pst.setString(3,staffPassword.getText());
pst.setString(4,staffTel.getText());
String value =staffPosition.getSelectedItem().toString();
pst.setString(5,value);
pst.setBytes(6,person_image);
pst.execute();
JOptionPane.showMessageDialog(null, "New Staff Added");
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
大家好,这是我添加员工记录的对话框。
但是,在将其保存到数据库之前,如何设置必须插入的所有数据(无数据字段可以为空)? (我想提醒用户,如果他或她没有输入所有数据。)
数据库中的所有数据我已经设置了“not null”,但即使数据为空,我仍然可以保存记录。
答案 0 :(得分:0)
您可以使用staffID.getText().trim().isEmpty()
检查JTextField是否为空,使用JOptionPane消息对话框提醒用户。一个例子就是:
public static void main(String[] args) {
int p = JOptionPane.showConfirmDialog(null, "Are you sure to add this staff?", "Comfirmation", JOptionPane.YES_NO_OPTION);
if (p == 0) {
if (staffID.getText().trim().isEmpty()) {// validate user input
JOptionPane.showMessageDialog(null, "Please enter staff ID"); // remind user
} else if (staffName.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(null, "Please enter staff name");
} else if (staffPassword.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(null, "Please enter password");
} else if (staffTel.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(null, "Please enter staff telephone");
} else {
String sql = "Insert into login.createstaff (Staff_ID,Staff_Name,Staff_password,Staff_Tel,Staff_position,image) values (?,?,?,?,?,?)";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, staffID.getText());
pst.setString(2, staffName.getText());
pst.setString(3, staffPassword.getText());
pst.setString(4, staffTel.getText());
String value = staffPosition.getSelectedItem().toString();
pst.setString(5, value);
pst.setBytes(6, person_image);
pst.execute();
JOptionPane.showMessageDialog(null, "New Staff Added");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
}