Advertisement
Guest User

Untitled

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