Solved MySQL Connection Closing

Discussion in 'Spigot Plugin Development' started by DisCoder212, Jul 26, 2018.

  1. I am creating a table when my plugin starts up, and then after closing the connection -

    Code (Text):

    private Connection connection;

    private boolean isConnected() {
        return (connection == null ? false : true);
    }

    public void connect() {
        if (!isConnected()) {

            String host = plugin.getConfig().getString("Host");
            String port = plugin.getConfig().getString("Port");
            String database = plugin.getConfig().getString("Database");
            String username = plugin.getConfig().getString("Username");
            String password = plugin.getConfig().getString("Password");

            try {
                connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public void disconnect() {
        if (isConnected()) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public void createTable() {
        if (!isConnected()) {
            connect();
        }
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS players (UUID VARCHAR(100),RANK VARCHAR(100))");
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            disconnect();
        }
    }
     

    But for some reason I get an error saying
    Code (Text):

    > [18:56:02 WARN]: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
     
    Does anyone know why I am getting no operations allowed after connection closed? I'm doing the operation before the connection gets closed..?
     
  2. Perhaps you can log something to console at the beginning of each of those methods so that you can see when they're being called. You can create a new Exception and exception.printStackTrace() as well, this will show you what called the method.
     
  3. Just did that, the entire method gets ran completely through than an error occurs weird..?
     
  4. Is there some chance that there's an asynchronous task being started when you execute the SQL statement? It may be that when you execute the code then close the connection, that the that task hasn't completed.
     
    • Like Like x 1