I am trying to make login form with java and mysql. I have user database with one table, and userName and password field. I have my base UserBase class and my LoginFXMLController class. When I run it I get NullPointerException. When I debug it it shows null value on ps=conn.prepareStatment.
Here is my LoginFXMLController class:
public class LoginFXMLController implements Initializable {
@FXML
private Button okBtn;
@FXML
private Button exitBtn;
@FXML
private Label infoPassword;
@FXML
private TextField nameFld;
@FXML
private PasswordField passwordFld;
private Connection conn = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
/**
* Initializes the controller class.
*/
public void initialize(URL url, ResourceBundle rb) {
conn= UserBase.get();
}
// Akcija za ok dugme u login formi
public void okBtnAction(ActionEvent event) throws SQLException, IOException {
String userName = nameFld.getText().trim();
String password = passwordFld.getText().trim();
String sql = "SELECT * user WHERE userName = ? AND password = ?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, userName);
ps.setString(2, password);
rs = ps.executeQuery();
if (rs.next()) {
Parent root = FXMLLoader.load(getClass().getResource("CoreAppFXML.fxml"));
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.setTitle("Main");
stage.show();
Stage login = (Stage) exitBtn.getScene().getWindow();
login.close();
} else {
wrongInputFXML();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void wrongInputFXML() throws IOException {
Parent root = FXMLLoader.load(getClass().getResource(
"WrongUsernameFXML.fxml"));
Stage errorStage = new Stage();
errorStage.setScene(new Scene(root));
errorStage.setTitle("Error");
errorStage.centerOnScreen();
errorStage.show();
}
// Akcija za exit dugme u login formi
public void exitBtnAction(ActionEvent event) {
Stage stage = (Stage) exitBtn.getScene().getWindow();
stage.close();
}
}
And my UserBase class:
public class UserBase {
private static Connection connection;
// Pristupa drajveru u JAR fajlu
private static Connection createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(
"jdbc:mysql://localhost:3306/user", "root", "");
} catch (Exception e) {
return null;
}
}
public static Connection get() {
if (connection == null) {
connection = createConnection();
}
return connection;
}
I am beginner in this so take it easy.