Advertisement
Guest User

Untitled

a guest
Feb 3rd, 2016
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. public abstract class Database {
  2.  
  3. public abstract Connection getConnection();
  4. public abstract void connect();
  5. public abstract void disconnect();
  6. public abstract boolean isConnected();
  7.  
  8. }
  9.  
  10. public class MySQL extends Database {
  11.  
  12. private final String ip;
  13. private final int port;
  14. private final String database;
  15. private final String username;
  16. private final String password;
  17.  
  18. public MySQL(String ip, int port, String database, String username, String password) {
  19. this.ip = ip;
  20. this.port = port;
  21. this.database = database;
  22. this.username = username;
  23. this.password = password;
  24. }
  25.  
  26. private Connection connection;
  27.  
  28. @Override
  29. public Connection getConnection() {
  30. return connection;
  31. }
  32.  
  33. @Override
  34. public void connect() {
  35. if (isConnected()) {
  36. return;
  37. }
  38.  
  39. try {
  40. connection = DriverManager.getConnection("jdbc:mysql://" + ip + ":" + port + "/" + database, username, password);
  41. } catch (SQLException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45.  
  46. @Override
  47. public void disconnect() {
  48. if (isConnected()) {
  49. try {
  50. connection.close();
  51. connection = null;
  52. } catch (SQLException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. }
  57.  
  58. @Override
  59. public boolean isConnected() {
  60. if(connection == null) {
  61. return false;
  62. }
  63.  
  64. try {
  65. return connection.isClosed();
  66. } catch (SQLException e) {
  67. e.printStackTrace();
  68. }
  69.  
  70. return false;
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement