DataBank.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package me.km.databank;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import me.km.api.Module;
  7. import me.km.scheduler.SnuviScheduler;
  8. import net.minecraft.util.text.TextFormatting;
  9. public class DataBank extends Module
  10. {
  11. private final static DummyStatement DUMMY_STATEMENT = new DummyStatement();
  12. private Connection c;
  13. private final String user;
  14. private final String password;
  15. public DataBank(String mname, String prefix, TextFormatting color, String user, String password)
  16. {
  17. super(mname, prefix, color);
  18. this.user = user;
  19. this.password = password;
  20. }
  21. public boolean openDataBankConnection()
  22. {
  23. c = null;
  24. try
  25. {
  26. // The newInstance() call is a work around for some broken Java implementations
  27. Class.forName("com.mysql.jdbc.Driver").newInstance();
  28. c = DriverManager.getConnection("jdbc:mysql://localhost/minecraft?autoReconnect=true", user, password);
  29. this.sendToConsole("Die Verbindung wurde erfolgreich aufgebaut.");
  30. return true;
  31. }
  32. catch(ClassNotFoundException | IllegalAccessException | InstantiationException | SQLException ex)
  33. {
  34. this.sendWarningToConsole(ex.toString());
  35. return false;
  36. }
  37. }
  38. public void closeDataBankConnection()
  39. {
  40. try
  41. {
  42. c.close();
  43. this.sendToConsole("Die Verbindung wurde erfolgreich unterbrochen.");
  44. }
  45. catch (SQLException ex)
  46. {
  47. this.sendWarningToConsole(ex.getMessage());
  48. }
  49. catch (NullPointerException ex)
  50. {
  51. }
  52. }
  53. public Statement createStatement() throws SQLException
  54. {
  55. if(c == null)
  56. {
  57. return DUMMY_STATEMENT;
  58. }
  59. return c.createStatement();
  60. }
  61. public void startReconnecting(SnuviScheduler scheduler)
  62. {
  63. scheduler.scheduleRepeatingTask(() ->
  64. {
  65. try(Statement stmt = createStatement())
  66. {
  67. // pointless query just for reconnecting
  68. stmt.executeUpdate("SHOW TABLES IN minecraft");
  69. }
  70. catch(SQLException ex)
  71. {
  72. sendToConsole("reconnect was done");
  73. }
  74. }, 100, 12000); // doing this every 10 minutes
  75. }
  76. }