Advertisement
Guest User

Untitled

a guest
Apr 30th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. package ru.dondays.api.database;
  2.  
  3. import ru.dondays.api.Main;
  4.  
  5. import java.sql.*;
  6.  
  7. public class SQLConnection
  8. implements DatabaseConnector {
  9.  
  10. private Connection connection;
  11. private String host;
  12. private String database;
  13. private String user;
  14. private String password;
  15.  
  16. private SQLConnection(String host, String user, String password) {
  17. this.host = host;
  18. this.user = user;
  19. this.password = password;
  20. }
  21.  
  22. public SQLConnection(String host, String user, String password, String database) {
  23. this(host, user, password);
  24. this.database = database;
  25. }
  26.  
  27. public Connection getConnection() throws SQLException {
  28. if(this.connection == null || this.connection.isClosed()) {
  29. this.connect();
  30. }
  31.  
  32. return this.connection;
  33. }
  34.  
  35. public void connect() throws SQLException {
  36. try {
  37. this.connection = DriverManager.getConnection("JDBC:mysql://" + this.host + ":3306/" + this.database + "?useUnicode=true&characterEncoding=UTF-8&" + "user=" + this.user + "&password=" + this.password);
  38. } catch(SQLException var2) {
  39. Main.getInstance().getLogger().info("При соединении с базой данных (" + this.host + ", " + this.database + ") произошла ошибка - " + var2.getMessage());
  40. var2.printStackTrace();
  41. }
  42. }
  43.  
  44. public void execute(String sql) throws SQLException {
  45. Statement statement = null;
  46. try {
  47. statement = this.getConnection().createStatement();
  48. statement.executeUpdate(sql);
  49. } finally {
  50. if(statement != null) {
  51. statement.close();
  52. }
  53. }
  54. }
  55.  
  56. public ResultSet executeQuery(String sql) throws SQLException {
  57. Statement statement = null;
  58. ResultSet rs = null;
  59. try {
  60. statement = this.getConnection().createStatement();
  61. rs = statement.executeQuery(sql);
  62. } finally {
  63. if(rs != null) {
  64. while(rs.isClosed()) {
  65. if(statement != null) statement.close();
  66. }
  67. }
  68. }
  69. return rs;
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement