Guest User

Untitled

a guest
Jan 29th, 2017
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. package mysql;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8.  
  9. public class MySQL
  10. extends Database
  11. {
  12. private final String user;
  13. private final String database;
  14. private final String password;
  15. private final String port;
  16. private final String hostname;
  17. private Connection connection;
  18.  
  19. public MySQL(String hostname, String port, String database, String username, String password)
  20. {
  21. this.hostname = hostname;
  22. this.port = port;
  23. this.database = database;
  24. this.user = username;
  25. this.password = password;
  26. this.connection = null;
  27. }
  28.  
  29. public Connection forceConnection()
  30. throws SQLException, ClassNotFoundException
  31. {
  32. Class.forName("com.mysql.jdbc.Driver");
  33. this.connection =
  34. DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" +
  35. this.database, this.user, this.password);
  36. return this.connection;
  37. }
  38.  
  39. public Connection openConnection()
  40. throws SQLException, ClassNotFoundException
  41. {
  42. if (checkConnection()) {
  43. return this.connection;
  44. }
  45. Class.forName("com.mysql.jdbc.Driver");
  46. this.connection =
  47. DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" +
  48. this.database, this.user, this.password);
  49. return this.connection;
  50. }
  51.  
  52. public boolean checkConnection()
  53. throws SQLException
  54. {
  55. return (this.connection != null) && (!this.connection.isClosed());
  56. }
  57.  
  58. public Connection getConnection()
  59. {
  60. return this.connection;
  61. }
  62.  
  63. public boolean closeConnection()
  64. throws SQLException
  65. {
  66. if (this.connection == null) {
  67. return false;
  68. }
  69. this.connection.close();
  70. this.connection = null;
  71. return true;
  72. }
  73.  
  74. public ResultSet querySQL(String query)
  75. throws SQLException, ClassNotFoundException
  76. {
  77. if (checkConnection()) {
  78. openConnection();
  79. }
  80. Statement statement = this.connection.createStatement();
  81. return statement.executeQuery(query);
  82. }
  83.  
  84. public int updateSQL(String query)
  85. throws SQLException, ClassNotFoundException
  86. {
  87. if (checkConnection()) {
  88. openConnection();
  89. }
  90. Statement statement = this.connection.createStatement();
  91. int i = statement.executeUpdate(query);
  92. statement.close();
  93.  
  94. return i;
  95. }
  96. }
Add Comment
Please, Sign In to add comment