Advertisement
Guest User

ConnectionProvider

a guest
Nov 20th, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. package com.ivasileuski.shop.connection;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.sql.SQLException;
  8. import java.util.Properties;
  9.  
  10. public class ConnectionProvider {
  11. private static final String DB_PROPS_PATH = "/db/db.properties";
  12. private String driver;
  13. private String url;
  14. private String username;
  15. private String password;
  16. private Connection jdbcConnection;
  17.  
  18. public static ConnectionProvider instance;
  19.  
  20. public ConnectionProvider() throws SQLException {
  21. Properties properties = new Properties();
  22. InputStream inputStream = ClassLoader.class.getResourceAsStream(DB_PROPS_PATH);
  23. try {
  24. if (inputStream != null) {
  25. properties.load(inputStream);
  26. inputStream.close();
  27. }
  28. } catch (IOException exception) {
  29. exception.printStackTrace();
  30. }
  31. driver = properties.getProperty("db.driver");
  32. url = properties.getProperty("db.url");
  33. username = properties.getProperty("db.username");
  34. password = properties.getProperty("db.password");
  35. try {
  36. Class.forName("org.h2.Driver");
  37. } catch (ClassNotFoundException e) {
  38. e.printStackTrace();
  39. }
  40. this.connect();
  41. }
  42.  
  43. public String getValue () {
  44. return url;
  45. }
  46.  
  47. public Connection getConnection() throws SQLException {
  48. return jdbcConnection;
  49. }
  50.  
  51. public void connect() throws SQLException {
  52. if (jdbcConnection == null || jdbcConnection.isClosed()) {
  53. jdbcConnection = DriverManager.getConnection(
  54. url, username, password);
  55. }
  56. }
  57.  
  58. public void disconnect() throws SQLException {
  59. if (jdbcConnection != null && !jdbcConnection.isClosed()) {
  60. jdbcConnection.close();
  61. }
  62. }
  63.  
  64. public static ConnectionProvider getInstance() throws SQLException {
  65. if (instance == null) {
  66. instance = new ConnectionProvider();
  67. }
  68. return instance;
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement