JavaFX MySQL 连接示例
在 JavaFX 和 MySQL 之间建立连接可以通过管理数据库操作的专用类来实现。下面是此类的一个示例:
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. }
此类建立与 MySQL 数据库的连接,并提供用于检索、添加、更新和删除“person”表中的数据。您可以通过创建实例并调用适当的方法与数据库交互来在 JavaFX 应用程序中使用此类。
以上是如何连接JavaFX与MySQL进行数据库操作?的详细内容。更多信息请关注PHP中文网其他相关文章!