无法使用 javaFX 连接到联机 mysql 数据库

Unable to connect to online mysql database using javaFX

我最近做了一个项目,涉及在 java 中使用 Swing 在线连接到 mysql 数据库。然后我决定将项目转换为 javaFX 并尝试复制代码以连接到 mysql 数据库。

这是我的代码:

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

这是 FXML 文件的代码

<?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>


但是,当我点击 运行 时,它就崩溃了,并且我收到错误消息“Java SE 二进制平台已停止工作”。它在我之前使用 swing 的应用程序中运行良好。切换到 javafx 时我所做的唯一更改是我使用 jdk 1.8 而不是 jdk 11,因为我被迫使用 netbeans 8.2,而 netbeans 8.2 似乎没有支持 jdk 11(我以前的项目就是用它开发的)。

我刚遇到同样的问题并重写了我的 SQL 连接库。 也许您可以将它用于您的项目,它在本地和在线对我都适用。

我的 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;
    }

}

当然记得包含 mysql.jar 文件。我使用“mysql-连接器-java-8.0.26.jar”。但是我看到你已经有了这个。

那么你可以使用类似这样的方法..

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

希望对您有所帮助 ;)