Home > Database > Mysql Tutorial > body text

How to Connect a JavaFX Application to a MySQL Database and Display Data in a TableView?

Linda Hamilton
Release: 2024-11-25 05:29:14
Original
711 people have browsed it

How to Connect a JavaFX Application to a MySQL Database and Display Data in a TableView?

JavaFX MySQL Database Connection

Connecting JavaFX applications to MySQL databases requires a specific class that handles the connection and data retrieval. Here's a simple example:

PersonDataAccessor:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

import java.util.List;
import java.util.ArrayList;

public class PersonDataAccessor {

    private Connection connection;

    // Constructor
    public PersonDataAccessor(String driverClassName, String dbURL, String user, String password) throws SQLException, ClassNotFoundException {
        Class.forName(driverClassName);
        connection = DriverManager.getConnection(dbURL, user, password);
    }

    // Close connection
    public void shutdown() throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }

    // Get person list
    public List<Person> getPersonList() throws SQLException {
        try (
            Statement stmnt = connection.createStatement();
            ResultSet rs = stmnt.executeQuery("select * from person");
        ) {
            List<Person> personList = new ArrayList<>();
            while (rs.next()) {
                String firstName = rs.getString("first_name");
                String lastName = rs.getString("last_name");
                String email = rs.getString("email_address");
                Person person = new Person(firstName, lastName, email);
                personList.add(person);
            }
            return personList;
        }
    }

}
Copy after login

This class handles the connection establishment, query execution, and data retrieval. The getPersonList() method queries the "person" table in the database and converts the retrieved data into a list of Person objects.

Person Model (data representation):

import javafx.beans.property.StringProperty;
import javafx.beans.property.SimpleStringProperty;

public class Person {

    private StringProperty firstName = new SimpleStringProperty(this, "firstName");
    public StringProperty firstNameProperty() {
        return firstName;
    }
    public String getFirstName() {
        return firstNameProperty().get();
    }
    public void setFirstName(String firstName) {
        firstNameProperty().set(firstName);
    }

    private StringProperty lastName = new SimpleStringProperty(this, "lastName");
    public StringProperty lastNameProperty() {
        return lastName;
    }
    public String getLastName() {
        return lastNameProperty().get();
    }
    public void setLastName(String lastName) {
        lastNameProperty().set(lastName);
    }

    private StringProperty email = new SimpleStringProperty(this, "email");
    public StringProperty emailProperty() {
        return email;
    }
    public String getEmail() {
        return emailProperty().get();
    }
    public void setEmail(String email) {
        emailProperty().set(email);
    }

    public Person() {}

    public Person(String firstName, String lastName, String email) {
        setFirstName(firstName);
        setLastName(lastName);
        setEmail(email);
    }

}
Copy after login

This class defines the Person object with properties for firstName, lastName, and email.

UI Class (displays data in a table):

import javafx.application.Application;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class PersonTableApp extends Application {

    private PersonDataAccessor dataAccessor;

    @Override
    public void start(Stage primaryStage) throws Exception {
        dataAccessor = new PersonDataAccessor(...); // Provide DB connection details

        TableView<Person> personTable = new TableView<>();
        TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
        firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
        TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
        lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
        TableColumn<Person, String> emailCol = new TableColumn<>("Email");
        emailCol.setCellValueFactory(new PropertyValueFactory<>("email"));

        personTable.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
        personTable.getItems().addAll(dataAccessor.getPersonList());

        BorderPane root = new BorderPane();
        root.setCenter(personTable);
        Scene scene = new Scene(root, 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    @Override
    public void stop() throws Exception {
        if (dataAccessor != null) {
            dataAccessor.shutdown();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Copy after login

This class initializes the UI and displays the Person objects in a TableView.

By following these steps, you can create a JavaFX application that successfully connects to a MySQL database, retrieves data, and displays it in a user-friendly table.

The above is the detailed content of How to Connect a JavaFX Application to a MySQL Database and Display Data in a TableView?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template