【问题标题】:How to connect PostgreSQL with JavaFX [closed]如何将 PostgreSQL 与 JavaFX 连接起来 [关闭]
【发布时间】:2021-12-07 16:00:00
【问题描述】:

我想将我的 PostgreSQL 数据库连接到 JavaFX,当用户在文本字段中输入命令时,标签或表格视图会显示查询结果。这是我收到空连接错误的代码。

附:我添加的 UI 图片可以更好地说明情况

public class ListController {

    @FXML
    public TextField sqlTextField;
    @FXML
    public Label textLabel;

    public void handleSaveButton(ActionEvent actionEvent) {
    }

    public void handleRunButton(ActionEvent actionEvent1) throws SQLException {

        ConnectionClass connectionClass = new ConnectionClass();
        Connection connection = connectionClass.getConnection();

        String sql = sqlTextField.getText() + ";";
        Statement statement = connection.createStatement();
        statement.executeUpdate(sql);
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
            textLabel.setText(resultSet.getString(1));

        }
    }
}

【问题讨论】:

标签: java postgresql user-interface javafx jdbc


【解决方案1】:

我不明白你所说的ConnectionClass 是什么意思。

在 JDBC 中,使用 DataSource 的实现来连接到您的数据库。

This JDBC driver 为 Postgres 提供 a couple of implementations。你可能会想要org.postgresql.ds.PGSimpleDataSource

PGSimpleDataSource dataSource = new PGSimpleDataSource();

String[] serverAddresses = { "your-server-address-goes-here" };
dataSource.setServerNames( serverAddresses );
int[] serverPortNumbers = { your-port-number-goes-here };
dataSource.setPortNumbers( serverPortNumbers );
dataSource.setSslCert( cert );
dataSource.setDatabaseName( "your-database-name" );
dataSource.setUser( "your-database-user-name" );
dataSource.setPassword( "your-password-goes-here" );

return dataSource ;  // Return as a `DataSource` type of object.

您在其他地方的代码可以请求连接。使用try-with-resources 语法自动关闭您的连接(以及结果集等其他资源)。

try (
    Connection conn = dataSource.getConnection() ;
)
{
    // … Use `conn` Connection object to access database.
}
catch ( SQLException e )
{
    e.printStackTrace();
}

更多讨论请见my Answer

当然,将数据库密码嵌入 JavaFX 应用程序是不安全的。一种替代方法是使用JNDI 访问诸如LDAP 服务器之类的服务以获取数据库凭据。但那完全是另一回事了。

盲目地执行用户键入的 SQL 语句也是不安全的。这应该永远在真实系统中完成。了解SQL injection 攻击。但是,如果您只是在尝试,那就玩得开心。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-17
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 2014-12-05
    • 2020-04-02
    相关资源
    最近更新 更多