Home >Database >Mysql Tutorial >How to Connect JavaFX to MySQL for Database Operations?

How to Connect JavaFX to MySQL for Database Operations?

Susan Sarandon
Susan SarandonOriginal
2024-11-24 15:29:10677browse

How to Connect JavaFX to MySQL for Database Operations?

JavaFX MySQL Connection Example

Establishing a connection between JavaFX and MySQL can be achieved through a dedicated class that manages the database operations. Here's an example of such a class:

PersonDataAccessor.java:

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 {

    // Assuming you have a "person" table with columns: id, first_name, last_name, email

    private Connection connection;

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

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

    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()) {
                int id = rs.getInt("id");
                String firstName = rs.getString("first_name");
                String lastName = rs.getString("last_name");
                String email = rs.getString("email");
                Person person = new Person(id, firstName, lastName, email);
                personList.add(person);
            }
            return personList;
        }
    }

    // Other methods for adding, updating, deleting persons, etc.

}

This class establishes a connection to the MySQL database and provides methods for retrieving, adding, updating, and deleting data from the "person" table. You can use this class in your JavaFX application by creating an instance and calling the appropriate methods to interact with the database.

The above is the detailed content of How to Connect JavaFX to MySQL for Database Operations?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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