Home >Database >Mysql Tutorial >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!