我有插入一條記錄到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