I have written these two classes. First, is the GUI I created and second is the JDBC connector between Java and SQL. I want to add an update statement in my code but no matter what I have tried I get the same error.
This is for a university project. I have already tried Prepared Statement instead of Statement, I have test this query:
String query = "UPDATE user SET name = 'TEST' WHERE username = 'cleogeo'";
instead of the one in the code and I know connection and getters and setters are working properly since the rest of the program executes fine.
CandidateUI Class (GUI): Here I create "edit and save mode" in the GUI to make it easier for the user to change his profile settings.
private void EditAndSaveActionPerformed(java.awt.event.ActionEvent evt) {
counter++;
if(counter%2 == 1){
changePassword.setEditable(true);
changeName.setEditable(true);
changeSurname.setEditable(true);
changeEmail.setEditable(true);
changeBio.setEditable(true);
EditAndSave.setText("Save");
} else {
changePassword.setEditable(false);
changeName.setEditable(false);
changeSurname.setEditable(false);
changeEmail.setEditable(false);
changeBio.setEditable(false);
EditAndSave.setText("Edit");
newPassword = changePassword.getText();
newName = changeName.getText();
newSurname = changeSurname.getText();
newEmail = changeEmail.getText();
newBio = changeBio.getText();
iCRUDImpl.getCandidateUI(changeUsername.getText());
}
}
Then I create getters and setters for every "new" variable.
ICRUDImpl Class (JDBC):
public CandidateUI getCandidateUI(String username) {
try{
CandidateUI candidateUI = new CandidateUI();
Statement statement = connection.createStatement();
String query = "UPDATE user SET password = '" + candidateUI.getNewPassword() + "', name = '" + candidateUI.getNewName() + "', surname = '" + candidateUI.getNewSurname() + "', email = '" + candidateUI.getNewEmail() + "' WHERE username = '" + username + "';UPDATE candidate SET bio = '" + candidateUI.getNewBio() + "'";
statement.executeUpdate(query);
return candidateUI;
} catch (SQLException e) {
return null;
}
}
The error I get is a java.lang.NullPointerException in line
Statement statement = connection.createStatement();
of JDBC.
Here is also my Connection Method:
public void openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/erecruit", "root", "");
System.out.println("Connection established successfully with the database server.");
} catch (ClassNotFoundException | SQLException e) {
System.err.println("Error: " + e.getMessage());
}
}