Unable to connect to online mysql database using javaFX

Issue

I recently made a project which involved connecting to a mysql database online using Swing in java. I then decided to convert the project to javaFX and tried to replicate the code to connect to a mysql database.

This is my code:

package virtlib;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import java.sql.*;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


/**
 *
 * @author param
 */
public class FXMLDocumentController implements Initializable {
    private Connection con;
    private Statement st;
    private ResultSet rs;
     private ResultSet rs2;
    private Stage stage;
    @FXML
    private Label label;
    @FXML
    private Button login;
    @FXML
    private PasswordField password;
    @FXML
    private TextField username;
    
    @FXML
    private void handleButtonAction(ActionEvent event) {
     
        try{
            
            Class.forName("com.mysql.cj.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://db4free.net:3306/parambase","theboss12k","Password");//Password has been changed
            st=con.createStatement();
            label.setText("Connection success !");
            
        }
        catch(Exception ae){
           label.setText("We are unable to connect to our servers. Please check your internet connection and restart the app !");
        }
        
    
    
    }
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }    
    
}

This is the code of the FXML file

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.Pane?>

<AnchorPane id="AnchorPane" prefHeight="494.0" prefWidth="409.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/16" fx:controller="virtlib.FXMLDocumentController">
    <children>
        <Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" prefHeight="18.0" prefWidth="276.0" />
      <Pane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="297.0" prefWidth="410.0" style="-fx-background-color: white;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <children>
              <Button fx:id="login" layoutX="129.0" layoutY="331.0" onAction="#handleButtonAction" prefHeight="26.0" prefWidth="70.0" text="Login" />
            <PasswordField fx:id="password" layoutX="129.0" layoutY="276.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="26.0" prefWidth="222.0" />
            <TextField fx:id="username" layoutX="129.0" layoutY="229.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="26.0" prefWidth="222.0" />
            <Label layoutX="40.0" layoutY="280.0" text="Password" />
            <Label layoutX="38.0" layoutY="233.0" text="Username" />
            <Label layoutX="129.0" layoutY="400.0" prefHeight="17.0" prefWidth="222.0" textFill="#e70d1b" />
         </children>
      </Pane>
    </children>
</AnchorPane>


However, when I hit run, it just crashes, and I get the error that "Java SE Binary platform has stopped working". It was working perfectly in my previous application using swing. The only change I made when switching to javafx was that I used jdk 1.8 instead of jdk 11, as I was forced to use netbeans 8.2, and netbeans 8.2 doesn’t seem to support jdk 11 (Using which my previous project was developed).

Solution

I just went through the same issue and rewrote my SQL connection lib.
Maybe you can use it for your project, it works for me both local and online.

My HandleSqlBdSimple class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

public class HandleSqlDbSimple {

    private Connection connection = null;
    private Statement statement;
    private ResultSet resultSet;
    private boolean isConnected = false;

    // Creating objects for connection
    private String aHost;
    private String aPort;
    private String aDatabase;
    private String aUser;
    private String aPassword;
    private String aDriver;
    private String aPrefix;

    public HandleSqlDbSimple(String host, String port, String database, String user, String psw, String driver, String prefix){
        this.aHost = host;
        this.aPort = port;
        this.aDatabase = database;
        this.aUser = user;
        this.aPassword = psw;
        this.aDriver = driver;
        this.aPrefix = prefix;

        //      Connection example:
        //      aHost = "localhost";
        //      aPort = "3306";
        //      aDatabase = "testdb";
        //      aUser = "root";
        //      aPassword = "kungfu";
        //      aDriver = "com.mysql.jdbc.Driver";
        //      aPrefix = "jdbc:mysql:";
    }

    private synchronized void loadConnection(){

        try {
            Class.forName(aDriver);

            connection = DriverManager.getConnection(aPrefix + "//" + aHost + ":" + aPort + "/" + aDatabase +
                    "?user=" + aUser + "&password=" + aPassword);

            isConnected = true;

        } catch (ClassNotFoundException e) {
            isConnected=false;
            e.printStackTrace();
        } catch (SQLException e) {
            isConnected=false;
            e.printStackTrace();
        }

        if(isConnected){
            try {
                connection.setAutoCommit(false);
                statement = connection.createStatement();
                statement.setFetchSize(100000);
                System.out.println("Connection open!");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("Is not connected!");
        }
    }

    private synchronized void closeConnection(){
        if (isConnected) {
            try {
                if (resultSet != null){
                    resultSet.close();
                };
                statement.close();
                connection.close();
                System.out.println("Connection Closed!");
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("My Error in connection close: " + e);
            }
        }
    }

    public boolean writeToDB(String stmt){
        boolean aResult = false;

        // Open the connection to the database
        loadConnection();

        try {
            if(isConnected){
                statement.executeUpdate(stmt);
                connection.commit();

                aResult = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // Close the DB again
        closeConnection();

        return aResult;
    }

    public String[][] readFromDB(String stmt) {
        String[][] data = null;
        Vector<String[]> aVectorBuffer = new Vector<String[]>();
        String[] colData = null;

        loadConnection();

        if(isConnected){

            try {
                resultSet = statement.executeQuery(stmt);
                ResultSetMetaData aResultSetMetaData = resultSet.getMetaData();

                // Get number of columns
                int aColCount = aResultSetMetaData.getColumnCount();
                colData = new String[aColCount];

                while (resultSet.next()) {

                    for(int col=0; col<aColCount; col++){

                        colData[col] = resultSet.getString(col+1);

                    }

                    aVectorBuffer.add(colData);
                    colData = new String[aColCount];
                }

                closeConnection();

            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        data = new String[aVectorBuffer.size()][colData.length];

        for(int row=0;row<aVectorBuffer.size(); row++){
            for(int col=0;col<colData.length; col++){

                data[row][col] = aVectorBuffer.get(row)[col];

            }
        }

        return data;
    }

}

Remember to include the mysql .jar file ofcourse. I use the "mysql-connector-java-8.0.26.jar". But i see you already have this.

Then you could use a method something like this..

@FXML
    private void handleButtonAction(ActionEvent event) {
     
        HandleSqlDbSimple db = new HandleSqlDbSimple("host", "port", "database", "user", "psw", "driver", "prefix");
        
        db.writeToDB("your write statement");
        
        String[][] result = db.readFromDB("your read statement here");
        
    }

Hope it helps 😉

Answered By – Bl4z3u5

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published