Connecting JavaFX to MySQL Made Easy: A Database Connectivity Class
When it comes to connecting JavaFX applications to MySQL databases, simplicity and efficiency are crucial. In this article, we'll delve into a comprehensive solution by providing a class specifically designed for establishing a MySQL connection and retrieving data into a table.
Our proposed class, known as PersonDataAccessor, embodies a straightforward approach to database interaction. It consists of three methods:
To establish the connection, the class constructor requires four parameters:
To use this class, you'll need to create an instance and call the getPersonList() method to populate your TableView with data. Once the data is displayed, you can utilize the other methods to manage the database as needed.
Here's an example of how to implement this solution:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class PersonDataAccessor { 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 { List<Person> personList = new ArrayList<>(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM person"); while (resultSet.next()) { String firstName = resultSet.getString("first_name"); String lastName = resultSet.getString("last_name"); String email = resultSet.getString("email"); Person person = new Person(firstName, lastName, email); personList.add(person); } statement.close(); resultSet.close(); return personList; } public void addPerson(Person person) throws SQLException { String firstName = person.getFirstName(); String lastName = person.getLastName(); String email = person.getEmail(); Statement statement = connection.createStatement(); statement.executeUpdate("INSERT INTO person (first_name, last_name, email) VALUES ('" + firstName + "', '" + lastName + "', '" + email + "')"); statement.close(); } }
With this class at your disposal, connecting your JavaFX application to a MySQL database and managing data retrieval and insertion becomes a breeze. Enjoy seamless database integration and focus on building robust and data-centric applications without any unnecessary headaches!
The above is the detailed content of How Can I Easily Connect My JavaFX Application to a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!