JavaFX controller that fetches the username and password from a MySQL database using JDBC:

Posted on

JavaFX controller class that fetches the username and password from a MySQL database named “biharigraphic” and a table named “users” using JDBC:

import java.sql.*;

import javafx.fxml.FXML;
import javafx.scene.control.*;

public class LoginController {

    private TextField usernameField;

    private PasswordField passwordField;

    private Label messageLabel;

    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/biharigraphic";

    // Database credentials
    static final String USER = "root";
    static final String PASS = "password";

    public void login() {
        String username = usernameField.getText();
        String password = passwordField.getText();

        Connection conn = null;
        Statement stmt = null;
        try {
            // Register JDBC driver

            // Open a connection
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // Execute a query
            stmt = conn.createStatement();
            String sql = "SELECT * FROM users WHERE username='" + username + "' AND password='" + password + "'";
            ResultSet rs = stmt.executeQuery(sql);

            // Check if the username and password are correct
            if ( {
                messageLabel.setText("Login successful!");
            } else {
                messageLabel.setText("Invalid username or password.");

            // Clean-up environment
        } catch (SQLException se) {
            // Handle errors for JDBC
            messageLabel.setText("Database error.");
        } catch (Exception e) {
            // Handle errors for Class.forName
            messageLabel.setText("Unexpected error.");
        } finally {
            // Close resources
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
                // Ignore
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {


In this example, the login() method is called when the user clicks a login button in the UI. The method first gets the username and password entered by the user in the text fields. It then uses JDBC to connect to the MySQL database and execute a SELECT query to check if the username and password are correct. If the query returns a row, the login is successful; otherwise, an error message is displayed.

Note that you will need to replace the database URL, username, and password with your own values, and also make sure that you have the MySQL JDBC driver JAR file on your classpath.