Guest User

Untitled

a guest
Jul 6th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. package com.codemonkey.utils;
  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 MySQLManager {
  10.  
  11. private String host;
  12. private String port;
  13. private String database;
  14. private String user;
  15. private String password;
  16.  
  17. public MySQLManager(String host, String port, String database, String user, String password) {
  18. this.host = host;
  19. this.port = port;
  20. this.database = database;
  21. this.user = user;
  22. this.password = password;
  23. }
  24.  
  25. private Connection createConnection() {
  26. Connection connection;
  27. try {
  28. Class.forName("com.mysql.jdbc.Driver");
  29. connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, user,
  30. password);
  31. return connection;
  32. } catch (SQLException e) {
  33. System.out.println("Could not connect to MySQL server! because: " + e.getMessage());
  34. } catch (ClassNotFoundException e) {
  35. System.out.println("JDBC Driver not found!");
  36. }
  37. return null;
  38. }
  39.  
  40. public ResultSet executeQuery(String query) {
  41. Connection connection = createConnection();
  42. Statement statement = null;
  43. ResultSet set = null;
  44. try {
  45. statement = connection.createStatement();
  46. set = statement.executeQuery(query);
  47. return set;
  48. } catch (SQLException e) {
  49. e.printStackTrace();
  50. } finally { // Close in order: ResultSet, Statement, Connection.
  51. try {
  52. set.close();
  53. } catch (Exception e) {
  54. }
  55. try {
  56. statement.close();
  57. } catch (Exception e) {
  58. }
  59. try {
  60. connection.close();
  61. } catch (Exception e) {
  62. }
  63. }
  64. return null;
  65. }
  66.  
  67. public void executeUpdate(String update) {
  68. Connection connection = createConnection();
  69. Statement statement = null;
  70. try {
  71. statement = connection.createStatement();
  72. statement.executeUpdate(update);
  73. } catch (SQLException e) {
  74. e.printStackTrace();
  75. } finally {
  76. try {
  77. statement.close();
  78. } catch (Exception e) {
  79. }
  80. try {
  81. connection.close();
  82. } catch (Exception e) {
  83. }
  84. }
  85. }
  86. }
Add Comment
Please, Sign In to add comment