我有插入一条记录到MySQL数据库出了问题,只需查询没有得到执行,我不明白为什么捕获异常时,不打印任何错误。请有任何想法吗? 我已经检查了很多次拼写检查和表格本身,连接也起作用,因为它在我的登录窗口中使用,它出现在下面显示的窗口之前。MySQL的记录不保存
public class RegisterStudent implements Initializable{
@FXML
TextField txtID;
@FXML
TextField txtFirstName;
@FXML
TextField txtSecondName;
@FXML
TextField txtGender;
@FXML
TextField txtDOB;
@FXML
TextField txtAddress;
@FXML
TextField txtPostCode;
@FXML
TextField txtMobileNumber;
@FXML
Button btnRegister;
@FXML
Button btnClear;
Connection connection = null;
PreparedStatement preparedStatement = null;
// Set Clear Button.
@FXML
private void setBtnClear() {
txtID.clear();
txtFirstName.clear();
txtSecondName.clear();
txtGender.clear();
txtDOB.clear();
txtAddress.clear();
txtPostCode.clear();
txtMobileNumber.clear();
}
// Set Register Button - Saves student record to database.
@FXML
private void setBtnRegister(ActionEvent event) {
try {
if(txtFirstName.getText().trim().isEmpty() ||
txtSecondName.getText().trim().isEmpty() ||
txtGender.getText().trim().isEmpty() ||
txtDOB.getText().trim().isEmpty() || txtAddress.getText().trim().isEmpty()
|| txtPostCode.getText().trim().isEmpty() || txtMobileNumber.getText().trim().isEmpty()) {
DBUtilities.showErrorMsg("Error:", "All fields must be populated!");
}else {
connection = DBUtilities.getConnection();
String SQLQuery = "INSERT INTO student_details ('First_Name', 'Second_Name', 'Gender', 'Date_Of_Birth', 'Address', 'Post_Code', 'Mobile_Number')" + " VALUES (?, ?, ? ,? ,? ,? ,?)";
preparedStatement = connection.prepareStatement(SQLQuery);
preparedStatement.setString(1, txtFirstName.getText().trim());
preparedStatement.setString(2, txtSecondName.getText().trim());
preparedStatement.setString(3, txtGender.getText().trim());
preparedStatement.setString(4, txtDOB.getText().trim());
preparedStatement.setString(5, txtAddress.getText().trim());
preparedStatement.setString(6, txtPostCode.getText().trim());
preparedStatement.setString(7,
txtMobileNumber.getText().trim());
preparedStatement.executeUpdate();
DBUtilities.showInforMsg("Record Saved", "Record has been saved
successfully!");
}
}catch (Exception exception) {
//DBUtilities.showErrorMsg("Error:", "Record could not be saved!");
exception.printStackTrace();
}finally {
DBUtilities.closePreparedStatement(preparedStatement);
DBUtilities.closeConnection(connection);
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
btnRegister.setOnAction(this::setBtnRegister);
}
}
你一定得给至少某种错误消息。如果没有其他,请在catch块中放置一个断点并手动检查异常类型和异常消息。 –
我摆脱了括号,没有任何东西。断点是什么意思? – cris22tian
你应该抓住[的SQLException(https://docs.oracle.com/javase/7/docs/api/java/sql/SQLException.html),而不是例外,能够找出到底发生了什么错误。请参见[异常和SQLException之间的区别](http://stackoverflow.com/q/22944978/205233)上的答案。 – Filburt