From dec8b5031717f05c38b2e4a60e53464cd19083d6 Mon Sep 17 00:00:00 2001 From: Stijn Date: Wed, 17 Nov 2021 19:32:21 +0100 Subject: [PATCH] Changed database to not be static --- src/main/java/com/alttd/VillagerUI.java | 2 +- .../com/alttd/commands/database/Database.java | 51 ++++++++++++++----- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/alttd/VillagerUI.java b/src/main/java/com/alttd/VillagerUI.java index 9548fa9..2480a6a 100644 --- a/src/main/java/com/alttd/VillagerUI.java +++ b/src/main/java/com/alttd/VillagerUI.java @@ -36,7 +36,7 @@ public class VillagerUI extends JavaPlugin { WorthConfig.reload(); if (!setupEconomy()) return; - Database.init(); + Database.getDatabase().init(); Logger.info("--------------------------------------------------"); Logger.info("Villager UI started"); Logger.info("--------------------------------------------------"); diff --git a/src/main/java/com/alttd/commands/database/Database.java b/src/main/java/com/alttd/commands/database/Database.java index e26b3d9..26885ac 100644 --- a/src/main/java/com/alttd/commands/database/Database.java +++ b/src/main/java/com/alttd/commands/database/Database.java @@ -11,29 +11,56 @@ import java.sql.SQLException; public class Database { + private static Database instance = null; public static Connection connection = null; - public static void init() { //Not static so we know for sure it loads on time - String url = "jdbc:" + Config.DRIVER + - "://" + Config.IP + - ":" + Config.PORT + - "/" + Config.DATABASE_NAME + - "?autoReconnect=true&useSSL=false"; + private Database() { + + } + + public static Database getDatabase(){ + if (instance == null) + instance = new Database(); + return (instance); + } + + public void init() { try { - connection = DriverManager.getConnection(url, Config.USERNAME, Config.PASSWORD); + openConnection(); } catch (SQLException e) { e.printStackTrace(); - Logger.severe("Connection to database failed!"); - connection = null; - Logger.severe("Shutting down VillagerUI"); - Bukkit.getPluginManager().disablePlugin(VillagerUI.getInstance()); - return; } // Tables createUserPointsTable(); } + /** + * Opens the connection if it's not already open. + * @throws SQLException If it can't create the connection. + */ + private void openConnection() throws SQLException { + if (connection != null && !connection.isClosed()) { + return; + } + + synchronized (this) { + if (connection != null && !connection.isClosed()) { + return; + } + try { + Class.forName("com.mysql.cj.jdbc.Driver"); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + + connection = DriverManager.getConnection( + "jdbc:mysql://" + Config.IP + ":" + Config.PORT + "/" + Config.DATABASE_NAME + + "?autoReconnect=true&useSSL=false", + Config.USERNAME, Config.PASSWORD); + } + } + private static void createUserPointsTable() { try { String sql = "CREATE TABLE IF NOT EXISTS user_points(" +