Advertisement
Guest User

Untitled

a guest
May 24th, 2017
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. public class Database {
  2.  
  3. private final String HOST;
  4. private final int PORT;
  5. private final String DATABASE;
  6. private final String USERNAME;
  7. private final String PASSWORD;
  8.  
  9. private Connection connection;
  10.  
  11. public Database() {
  12. this.HOST = ConfigData.host;
  13. this.PORT = ConfigData.port;
  14. this.DATABASE = ConfigData.database;
  15. this.USERNAME = ConfigData.username;
  16. this.PASSWORD = ConfigData.password;
  17.  
  18. openConnection();
  19. queryUpdate("CREATE TABLE IF NOT EXISTS clients (uuid VARCHAR(36), name VARCHAR(16), achievements TEXT, PRIMARY KEY (uuid));");
  20. }
  21.  
  22. public Connection openConnection() {
  23. try {
  24. Class.forName("com.mysql.jdbc.Driver");
  25. return connection = DriverManager.getConnection("jdbc:mysql://" + HOST + ":" + PORT + "/" + DATABASE, USERNAME, PASSWORD);
  26. } catch(Exception e) {
  27. e.printStackTrace();
  28. }
  29. return null;
  30. }
  31.  
  32. public void closeConnection() {
  33. try {
  34. connection.close();
  35. } catch(SQLException e) {
  36. e.printStackTrace();
  37. } finally {
  38. connection = null;
  39. }
  40. }
  41.  
  42. public void queryUpdate(String query) {
  43. checkConnection();
  44. try(PreparedStatement statement = connection.prepareStatement(query)) {
  45. queryUpdate(statement);
  46. } catch(Exception e) {
  47. e.printStackTrace();
  48. }
  49. }
  50.  
  51. public void queryUpdate(PreparedStatement statement) {
  52. checkConnection();
  53. try {
  54. statement.executeUpdate();
  55. } catch(SQLException e) {
  56. e.printStackTrace();
  57. } finally {
  58. try {
  59. statement.close();
  60. } catch(SQLException e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. }
  65.  
  66. public ResultSet query(String query) {
  67. checkConnection();
  68. try {
  69. return query(connection.prepareStatement(query));
  70. } catch(Exception e) {
  71. e.printStackTrace();
  72. }
  73. return null;
  74. }
  75.  
  76. public ResultSet query(PreparedStatement statement) {
  77. checkConnection();
  78. try {
  79. return statement.executeQuery();
  80. } catch(SQLException e) {
  81. e.printStackTrace();
  82. }
  83. return null;
  84. }
  85.  
  86. private void checkConnection() {
  87. try {
  88. if(connection == null || !connection.isValid(10) || connection.isClosed()) {
  89. openConnection();
  90. }
  91. } catch(Exception e) {
  92. e.printStackTrace();
  93. }
  94. }
  95.  
  96. public Connection getConnection() {
  97. return connection;
  98. }
  99.  
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement