sql help

Status
This thread has been locked.

ZooStalk

Banned
Feedback score
0
Posts
106
Reactions
39
Resources
0
so I coded my own global tokens plugin it works great except the database will randomly loose connection and i add tokens during that and it wipes over the old token data im not sure whats wrong
Code:
    public void onEnable() {
        saveDefaultConfig();
        Tokens.MySQL = new MySQL(this.plugin, this.plugin.getConfig().getString(
                "database.host"), this.plugin.getConfig().getString(
                "database.port"), this.plugin.getConfig().getString(
                "database.database"), this.plugin.getConfig().getString(
                "database.username"), this.plugin.getConfig().getString(
                "database.password"));
        Tokens.c = Tokens.MySQL.openConnection();
        if (Tokens.c != null) {
            initializeDatabase();
            setupShop();
        }


        prefix = "&e&lTokens&f:&b ";
        chat_color = "&d";
        prefix_nocolor = "[" + this.plugin.getDescription().getName() + "] ";
        this.plname = this.plugin.getDescription().getName().toLowerCase();
        this.plugin.getLogger()
                .info(String
                        .format("[%s] Has been enabled!",
                                new Object[] { this.plugin.getDescription()
                                        .getName() }));
//        new BukkitRunnable()
//        {
//          public void run()
//          {
//        
//              Tokens.c = Tokens.MySQL.openConnection();
//            }         
//        }.runTaskTimer(this, 0L, 20L * 60 * 10);
}
Code:
    public void onDisable() {
        Tokens.MySQL.closeConnection();
        Tokens.c = null;
        this.plugin.getLogger()
                .info(String
                        .format("[%s] Has been disabled!",
                                new Object[] { this.plugin.getDescription()
                                        .getName() }));
    }
 
Banned forever. Reason: Scamming
PebbleHost
High performance, consistent uptime and fast support. Minecraft hosting that just works.

ZooStalk

Banned
Feedback score
0
Posts
106
Reactions
39
Resources
0
Yes, sure. the code you have posted is incredibly helpful. You have shown us exactly how you shouldn't initialize the database. also, you haven't posted the database initialization method at all.....
YourPlugin.java
Add to declarations
PHP:
private DatabaseConnector databaseConnector;
private DatabaseAPI databaseAPI;
private DatabaseManager databaseManager;
New methods
PHP:
    /**
     * Init Database Connection;
     */
    private boolean initDatabase() {

    try {
       this.databaseConnector = new DatabaseConnector(this);
    } catch (SQLException ex) {
       getLogger().severe("MySQL connection failed. Disabling plugin.");
       getServer().getPluginManager().disablePlugin(this);
       return false;
    }
    return true;

    }


    /**
     * Get Database Connector; For internal API use only
     *
     * @return DatabaseConnector instance
     */
    public DatabaseConnector getDatabaseConnector() {

    return databaseConnector;

    }

    /**
     * Get Database Application Programming Interface;
     *
     * @return DatabaseAPI instance
     */
    public DatabaseAPI getDatabaseAPI() {

    return this.databaseAPI;

    }

then add this to the onEnable
PHP:
if (!initDatabase())
       return;
this.databaseAPI = new DatabaseAPI(this);
this.databaseManager = new DatabaseManager(this);

DataBaseConnector.java
PHP:
package me.myiume.yourplugin.managers;

import java.sql.*;
import java.util.logging.Level;

import me.myiume.yourplugin.YourPlugin;

import org.apache.commons.lang.StringUtils;
import org.bukkit.configuration.file.FileConfiguration;


public class DatabaseConnector {
    private final YourPlugin plugin;
    private Connection connection;
    private ResultSet resultSet;
    private String databaseHost;
    private String databasePort;
    private String databaseName;
    private String databaseUser;
    private String databasePass;

    public DatabaseConnector(YourPlugin plugin) throws SQLException {
        this.plugin = plugin;
        this.connect();
    }

    public final void connect() throws SQLException {
        FileConfiguration config = this.plugin.getConfig();
        this.databaseHost = config.getString("MySQL.hostname");
        this.databasePort = String.valueOf(config.getInt("MySQL.port"));
        this.databaseName = config.getString("MySQL.database");
        this.databaseUser = config.getString("MySQL.username");
        this.databasePass = config.getString("MySQL.password");
        this.connection = DriverManager.getConnection(String.format("jdbc:mysql://%s:%s/%s", this.databaseHost, this.databasePort, this.databaseName), this.databaseUser, this.databasePass);
    }

    public void connect(String databaseHost, String databasePort, String databaseName, String databaseUser, String databasePass) {
        String url = String.format("jdbc:mysql://%s:%s/%s", databaseHost, databasePort, databaseName);
        try {
            this.connection = DriverManager.getConnection(url, databaseUser, databasePass);
        } catch (SQLException ex) {
            this.log(Level.SEVERE, String.format("Error whilst connecting to database '%s'", url), ex);
        }
    }

    public void disconnect() {
        try {
            this.connection.close();
        } catch (SQLException ex) {
            this.log(Level.SEVERE, "Error whilst disconnecting from database. Was the connection ever opened?", ex);
        }
    }

    public void reconnect() throws SQLException {
        this.connection.close();
        this.connect(this.databaseHost, this.databasePort, this.databaseName, this.databaseUser, this.databasePass);
    }

    private void checkConnection() {
        try {
            if (this.connection == null) {
                this.log(Level.WARNING, "Connection is null. You were never connected.");
                return;
            }

            if (!this.connection.isValid(2)) {
                this.reconnect();
            }
        } catch (SQLException ex) {
            this.log(Level.SEVERE, "Error whilst checking connection. Was the connection ever opened?", ex);
        }
    }

    public ResultSet executeQuery(String query, Object... parameters) {
        this.checkConnection();

        int parameterCount = parameters == null ? 0 : parameters.length;
        if (StringUtils.countMatches(query, "?") != parameterCount) {
            this.log(Level.SEVERE, "PreparedStatement Error: Incorrect number of '?' for number of insertUpdate locations!");
            return null;
        }

        try {
            PreparedStatement statement = this.connection.prepareStatement(query);
            Object parameter;

            for (int i = 0, j = 1; i < parameterCount; i++, j++) {
                parameter = parameters[i];

                if (parameter instanceof String) {
                    statement.setString(j, (String) parameter);
                } else if (parameter instanceof Integer) {
                    statement.setInt(j, (Integer) parameter);
                } else if (parameter instanceof Boolean) {
                    statement.setBoolean(j, (Boolean) parameter);
                } else {
                    statement.setObject(j, parameter);
                }
            }

            this.resultSet = statement.executeQuery();
            return this.resultSet;
        } catch (SQLException ex) {
            this.log(Level.SEVERE, "Error whilst querying database!", ex);
        }

        return null;
    }

    public int executeUpdate(String query, Object... parameters) {
        this.checkConnection();

        int parameterCount = parameters == null ? 0 : parameters.length;
        if (StringUtils.countMatches(query, "?") != parameterCount) {
            this.log(Level.SEVERE, "PreparedStatement Error: Incorrect number of '?' for number of insertUpdate locations!");
            return -1;
        }

        try {
            PreparedStatement statement = this.connection.prepareStatement(query);
            Object parameter;

            for (int i = 0, j = 1; i < parameterCount; i++, j++) {
                parameter = parameters[i];

                if (parameter instanceof String) {
                    statement.setString(j, (String) parameter);
                } else if (parameter instanceof Integer) {
                    statement.setInt(j, (Integer) parameter);
                } else if (parameter instanceof Boolean) {
                    statement.setBoolean(j, (Boolean) parameter);
                } else {
                    statement.setObject(j, parameter);
                }
            }

            int result = statement.executeUpdate();
            return result;
        } catch (SQLException ex) {
            this.log(Level.SEVERE, "Error whilst querying database!", ex);
        }

        return -1;
    }

    public Object buildAndFetchColumn(String query, String result, Object... parameters) {
        this.executeQuery(query, parameters);

        try {
            Object objectResult = this.resultSet.getObject(result);

            if (objectResult instanceof String) {
                return this.resultSet.getString(result);
            } else if (objectResult instanceof Integer) {
                return this.resultSet.getInt(result);
            } else if (objectResult instanceof Boolean) {
                return this.resultSet.getBoolean(result);
            }

            return objectResult;
        } catch (SQLException ex) {
            this.log(Level.SEVERE, "Could not retrieve data from fetch!", ex);
        }

        return null;
    }

    public ResultSet build(String query, Object... parameters) {
        this.executeQuery(query, parameters);
        return this.resultSet;
    }

    public ResultSet getResultSet() {
        return this.resultSet;
    }

    private void log(Level level, String message) {
        this.plugin.getLogger().log(level, String.format("[MySQL] %s", message));
    }

    private void log(Level level, String message, Throwable ex) {
        this.plugin.getLogger().log(level, message, ex);
    }

}

DatabaseAPI.java
PHP:
package me.myiume.yourplugin.managers;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;

import me.myiume.yourplugin.YourPlugin;


public class DatabaseAPI {
    private final YourPlugin plugin;
    private final DatabaseConnector database;

    public DatabaseAPI(YourPlugin plugin) {
        this.plugin = plugin;
        database = plugin.getDatabaseConnector();

    }

    /**
     * @param query
     * @param parameters
     */
    public void executeUpdate(String query, Object... parameters) {
        this.database.executeUpdate(query, parameters);

    }

    /**
     * @param query
     * @param parameters
     * @return ResultSet
     */
    public ResultSet executeQuery(String query, Object... parameters) {
        return this.database.executeQuery(query, parameters);
    }

    /**
     * Reconnect to Database;
     */
    public void reconnect() {
        try {
            this.database.reconnect();
        } catch (SQLException ex) {
            this.plugin.getLogger().log(Level.SEVERE, ex.getMessage());
        }
    }

    /**
     * Disconnect from Database;
     */
    public void disconnect() {
        this.database.disconnect();
    }

    /**
     * @param query
     * @param result
     * @param parameters
     */
    public void buildAndFetchColumn(String query, String result, Object... parameters) {
        this.buildAndFetchColumn(query, result, parameters);
    }
}

DatabaseManager.java
PHP:
package me.myiume.yourplugin.managers;

import org.bukkit.scheduler.BukkitRunnable;

import me.myiume.yourplugin.YourPlugin;

public class DatabaseManager {
    private final YourPlugin plugin;
    private DatabaseAPI databaseAPI;
    private String tableName;

    public DatabaseManager(YourPlugin plugin) {
    this.plugin = plugin;
    this.databaseAPI = this.plugin.getDatabaseAPI();
    this.tableName = this.plugin.getConfig().getString("MySQL.tablename");
    createTable();
    }

    private void createTable() {
    final String query = "CREATE TABLE IF NOT EXISTS " + tableName + "(`player_uuid` VARCHAR(60) UNIQUE NOT NULL, `player_name` varchar(16) NOT NULL)";
    new BukkitRunnable() {
       @Override
       public void run() {
        DatabaseManager.this.databaseAPI.executeUpdate(query);
       }
    }.runTaskAsynchronously(this.plugin);
    }
}

To query your database, all you have to do is instantiate the databaseAPI into the class you're going to use it, using the getDatabaseAPI() method from the plugin's main class, and then call the databaseAPI.executeQuery();

Hope this helps.
I got it i set it to reconnect to the database every 10 minutes havent had any problems since
 
Banned forever. Reason: Scamming
Status
This thread has been locked.
Top