Advertisement
Guest User

Untitled

a guest
Dec 29th, 2016
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. package me.wumptrax.sql;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DatabaseMetaData;
  5. import java.sql.DriverManager;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8.  
  9. public class MySQL {
  10. private static String user;
  11. private static String database;
  12. private static String password;
  13. private static String port;
  14. private static String hostname;
  15. private static Connection connection = null;
  16.  
  17. public static boolean checkTable(String name) {
  18. boolean exists = false;
  19. try {
  20. DatabaseMetaData meta = MySQL.getConnection().getMetaData();
  21. ResultSet res;
  22.  
  23. res = meta.getTables(null, null, "", new String[] { "TABLE" });
  24. while (res.next()) {
  25. if (res.getString("TABLE_NAME").equals(name))
  26. exists = true;
  27. }
  28. } catch (SQLException e) {
  29. e.printStackTrace();
  30. }
  31. return exists;
  32. }
  33.  
  34. public static void loadMySQLSettings() {
  35.  
  36. //TODO: CONFIG
  37.  
  38. }
  39.  
  40. public static Connection getConnection() {
  41. if (isConnected())
  42. return connection;
  43. else {
  44. System.out.println("[MySQL] Lost MySQL Connection. Reconnecting...");
  45. connect();
  46. return connection;
  47. }
  48. }
  49.  
  50. public static boolean isConnected() {
  51. try {
  52. return connection != null && connection.isValid(120);
  53. } catch (SQLException e) {
  54. e.printStackTrace();
  55. }
  56. return false;
  57. }
  58.  
  59. public static void connect() {
  60.  
  61. if (isConnected()) {
  62. try {
  63. connection.close();
  64. } catch (SQLException e) {
  65. }
  66. }
  67.  
  68. try {
  69. Class.forName("com.mysql.jdbc.Driver");
  70. connection = DriverManager.getConnection("jdbc:mysql://" + hostname + ":" + port + "/" + database, user,
  71. password);
  72. System.out.println("[MySQL] Connected to database!");
  73. } catch (SQLException e) {
  74. System.out.println("[MySQL] Could not connect to MySQL server! Because: " + e.getMessage());
  75. } catch (ClassNotFoundException e) {
  76. System.out.println("[MySQL] JDBC Driver not found!");
  77. }
  78.  
  79. }
  80.  
  81. public static void closeConnection() {
  82. if (connection != null) {
  83. try {
  84. connection.close();
  85. connection = null;
  86. } catch (SQLException e) {
  87. System.out.println("[MySQL] Error while closing the MySQL Connection!");
  88. e.printStackTrace();
  89. }
  90. }
  91. }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement