请使用 JavaFX MySQL 连接示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25651641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:00:38  来源:igfitidea点击:

JavaFX MySQL connection example please

mysqljavafx-2

提问by marcS

Can anyone give me one example of a class that connects JavaFX with MySQL, dont want Main class, have one, just want a example of a class that connects any application to a MySQL database and gets a row from that database into a table, searched the whole internet and i didn't find anything straight to the point i do not want anything fancy just something to get the job done please. Something clean and simple.

谁能给我一个将 JavaFX 与 MySQL 连接的类的示例,不需要 Main 类,有一个,只想要一个将任何应用程序连接到 MySQL 数据库并将该数据库中的一行放入表中的类的示例,已搜索整个互联网,我没有找到任何直截了当的东西,我不想要任何花哨的东西,只是为了完成工作。一些干净和简单的东西。

回答by James_D

At a minimum, you need three classes: one to represent your data, one for your UI, and one to manage the database connection. In a real app you'd need more than this, of course. This example follows the same basic example as the TableViewtutorial

至少,您需要三个类:一个用于表示您的数据,一个用于您的 UI,一个用于管理数据库连接。当然,在真正的应用程序中,您需要的不止这些。此示例遵循与教程相同的基本示例TableView

Suppose your database has a persontable with three columns, first_name, last_name, email_address.

假设您的数据库有一个person包含三列的表,first_name, last_name, email_address

Then you would write a Personclass:

然后你会写一个Person类:

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

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

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

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

    public Person() {}

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

}

A class to access the data from the database:

从数据库访问数据的类:

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 {

    // in real life, use a connection pool....
    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()) {
                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 ;
        } 
    }

    // other methods, eg. addPerson(...) etc
}

And then a UI class:

然后是一个 UI 类:

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 driverName, dbURL, user, password...

        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);
    }
}

(I just typed that in without testing, so there may be typos, missing imports, etc, but it should be enough to give you the idea.)

(我只是在没有测试的情况下输入了它,所以可能会有拼写错误、缺少导入等,但它应该足以让你了解这个想法。)

回答by Martin Pfeffer

In addition to the answer of James_D:

除了James_D的回答:

I wanted to connect to a remote (MySQL) database, so I changed the constructor and connected by url-only:

我想连接到远程(MySQL)数据库,所以我更改了构造函数并仅通过 url 连接:

public UserAccessor(String dbURL, String user, String password) throws SQLException, ClassNotFoundException {
    connection = DriverManager.getConnection(dbURL, user, password);
}

Init via:

初始化通过:

UserAccessor userAccessor = new UserAccessor(
   "jdbc:mysql://xxx.xxx.xxx.xxx:YOUR_PORT", "YOUR_DB_USER", "YOUR_PASSWORD")

Please note:You will also need to include the connector lib. I choosed mysql-connector-java-5.1.40-bin.jarwhich came with IntelliJ and was located under /Users/martin/Library/Preferences/IntelliJIdea2017.1/jdbc-drivers/MySQL Connector/J/5.1.40/mysql-connector-java-5.1.40-bin.jar

请注意:您还需要包含连接器库。我选择mysql-connector-java-5.1.40-bin.jar了 IntelliJ 附带的并且位于/Users/martin/Library/Preferences/IntelliJIdea2017.1/jdbc-drivers/MySQL Connector/J/5.1.40/mysql-connector-java-5.1.40-bin.jar

Kudos belong to James_D.

荣誉属于 James_D。