简体   繁体   中英

How does my executable JavaFX file connect to a MySQL database?

I've recently finished working on my first JavaFX app. It connects with a MySQL database that is set up on a local server. Before using the application I need to start the servers running using Xampp. Now I want to finally pack my app into an .exe file and use it. I'm a complete newbie when it comes to the servers and databases. My question is - what do I do to make my app connect with the database itself once the user opens it? Do I need to switch from a local host server to a remote server that will not require starting it each time?

My JavaFX app connects with MySQL using JDBC.

private static String url = "jdbc:mysql://localhost:3306/Finance?useSSL=false&serverTimezone=UTC";
    private static String login = "root";
    private static String password = "";

    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(url, login, password);
        return connection;
    }

You can test your connection with a method like this:

public boolean canConnect() {
    try {
        con = DriverManager.getConnection(url, login, password);
        //executed only if no errors are thrown
        return true;
    } catch (SQLException e) {
        e.printStackTrace();
        //can't connect
        return false;
    } finally {
        //close connection if it was successful
        try {
            if (con!=null) con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

by calling it in your main method, or in your first stage like this:

if (!canConnect()) {
    //notify the user
    //start xampp or check connection to local server
} //else proceed

If you want to deploy your application with Xampp, you need to make Xampp to autostart when pc boots up, so the user don't have to start it manually in each boot.
If you are wondering how to auto-start your MySQL service in Xampp, you can find it here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM