javafx连接mysql [英] javafx connection to mysql

查看:535
本文介绍了javafx连接mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在构建javafx应用程序,它将提供关于股票的信息。
以下是网站:
http://analiza.host-ed.me/

we are building javafx application which will be presenting information about stocks. Here is the website: http://analiza.host-ed.me/

但我们有一个巨大的问题。每个免费托管不允许远程mysql连接。还有我的问题。当我们的网站在服务器(我链接)是这个远程连接或本地连接?
当我们把这个javafx应用程序作为一个网站,它不能像在本地机器上的连接...
有什么解决方案吗?感谢帮助。
(我们需要使用免费托管,因为它只是一个学校项目..)

But we've got a huge problem. Every free hosting doesn't allow remote mysql connection. And there is my question. When our site is on the server (which i linked) is this remote connection or local connection? When we put this javafx app as a site it can't connect like it was on the local machine... Is there any solution? Thanks for help. (we need to use free hosting, because it's only a school project..)

推荐答案

从JavaFX。但是JavaFX在客户端上运行,而php通常在服务器上运行。您将需要从您的Java应用程序到MySQL的连接。由于您的托管提供商不允许您从Java客户端应用程序直接连接到数据库端口,您将需要一些其他方式来连接。

You can access MySQL from JavaFX. But JavaFX runs on a client and something like php usually runs on a server. You will need a connection from your java app to MySQL. As your hosting provider won't allow you to directly connect to the database port from your Java Client App, you will need some other way to connect.

您可以通过端口80,您可以运行servlet(或php服务器代码等)通过基于HTTP的REST接口拦截传入的流量和代理数据库调用,您可以在客户端本地安装数据库。

You could tunnel through port 80, you could run a servlet (or php server code, etc) to intercept incoming traffic and proxy database calls through a HTTP based REST interface or you could install the DB locally on the client.

我想假设,对于一个学校项目,每个客户端机器都有自己的数据库。在这种情况下,请使用像 H2 这样的轻量级Java数据库,而不是使用MySQL,通过将您的应用程序包含为jar作为依赖库,打包应用程序加上DB jar作为使用JavaFX打包工具签名的WebStart应用程序,并托管由托管提供商的打包工具生成的文件。

I'm going to assume, for a school project, it's ok for each client machine to have it's own database. In which case, instead of using MySQL, use a lightweight Java database like H2, bundle it with your app by including it's jar as a dependent library, package the app plus DB jar as a signed WebStart application using the JavaFX packaging tools and host the files generated by the packaging tools at your hosting provider.

更新

以下是在客户端计算机上使用本地H2数据库的示例应用程序。

Here is a sample application which uses a local H2 database on the client computer.

import java.sql.*;
import java.util.logging.*;
import javafx.application.Application;
import javafx.collections.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class H2app extends Application {
  private static final Logger logger = Logger.getLogger(H2app.class.getName());
  private static final String[] SAMPLE_NAME_DATA = { "John", "Jill", "Jack", "Jerry" };

  public static void main(String[] args) { launch(args); }

  @Override public void start(Stage stage) {
    final ListView<String> nameView = new ListView();

    final Button fetchNames = new Button("Fetch names from the database");
    fetchNames.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        fetchNamesFromDatabaseToListView(nameView);
      }
    });

    final Button clearNameList = new Button("Clear the name list");
    clearNameList.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        nameView.getItems().clear();
      }
    });

    VBox layout = new VBox(10);
    layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
    layout.getChildren().setAll(
      HBoxBuilder.create().spacing(10).children(
        fetchNames, 
        clearNameList    
      ).build(),      
      nameView
    );
    layout.setPrefHeight(200);

    stage.setScene(new Scene(layout));
    stage.show();
  }

  private void fetchNamesFromDatabaseToListView(ListView listView) {
    try (Connection con = getConnection()) {
      if (!schemaExists(con)) {
        createSchema(con);
        populateDatabase(con);
      }
      listView.setItems(fetchNames(con));
    } catch (SQLException | ClassNotFoundException ex) {
      logger.log(Level.SEVERE, null, ex);
    }
  }

  private Connection getConnection() throws ClassNotFoundException, SQLException {
    logger.info("Getting a database connection");
    Class.forName("org.h2.Driver");
    return DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
  }

  private void createSchema(Connection con) throws SQLException {
    logger.info("Creating schema");
    Statement st = con.createStatement();
    String table = "create table employee(id integer, name varchar(64))";
    st.executeUpdate(table);
    logger.info("Created schema");
  }

  private void populateDatabase(Connection con) throws SQLException {
    logger.info("Populating database");      
    Statement st = con.createStatement();      
    int i = 1;
    for (String name: SAMPLE_NAME_DATA) {
      st.executeUpdate("insert into employee values(i,'" + name + "')");
      i++;
    }
    logger.info("Populated database");
  }

  private boolean schemaExists(Connection con) {
    logger.info("Checking for Schema existence");      
    try {
      Statement st = con.createStatement();      
      st.executeQuery("select count(*) from employee");
      logger.info("Schema exists");      
    } catch (SQLException ex) {
      logger.info("Existing DB not found will create a new one");
      return false;
    }

    return true;
  }

  private ObservableList<String> fetchNames(Connection con) throws SQLException {
    logger.info("Fetching names from database");
    ObservableList<String> names = FXCollections.observableArrayList();

    Statement st = con.createStatement();      
    ResultSet rs = st.executeQuery("select name from employee");
    while (rs.next()) {
      names.add(rs.getString("name"));
    }

    logger.info("Found " + names.size() + " names");

    return names;
  }
}

有一个相应的NetBeans项目,此示例将生成可部署的应用程序。您可以在 webstart applet 模式。

There is a corresponding NetBeans project for this sample which will generate a deployable application. The project can be tested in webstart and applet mode.

对于示例,数据库已存储在用户的计算机(而不是从其下载应用程序的服务器),并在应用程序运行之间持续。

For the sample, the database is stored on the user's computer (not the server from which the application was downloaded) and persists between application runs.

确切的位置取决于jdbc连接初始化字符串。在我的示例的情况下,数据库进入用户的目录 jdbc:h2:〜/ test ,这是操作系统和用户特定的。在我的Windows的情况下,它最终在 C:\Users\john_smith\test.h2.db 。使用像 jdbc:h2:〜/ test 这样的jdbc连接字符串比诸如 jdbc:h2:C:\\ Baza ,因为其中的 C:\\ 字符串是特定于平台的,并且在非Windows系统上无法正常工作。有关h2 jdbc连接字符串的详细信息,请参阅h2手册中的连接设置

The exact location depends on the jdbc connection initialization string. In the case of my sample the database goes in the user's directory jdbc:h2:~/test, which is OS and User specific. In the case of me for Windows it ends up at C:\Users\john_smith\test.h2.db. Using a jdbc connection string such as jdbc:h2:~/test is preferable to a string such as jdbc:h2:C:\\Baza because a string with C:\\ in it is platform specific and won't work well on non-windows systems. For further information on h2 jdbc connection strings refer to the connections settings in the h2 manual.

h2系统的工作原理是,如果数据库文件已经存在,它将被重用,否则将创建一个新的数据库文件。如果修改数据库,关闭应用程序,然后在一周后再次加载应用程序,它就能够读取前一周创建的数据。

The h2 system works such that if the database file already exists, it is reused, otherwise a new database file is created. If you modify the database, shut the application down, then load the application again a week later, it is able to read the data created the week before.

这篇关于javafx连接mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆