Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.ivasileuski.shop.connection;
- import java.io.IOException;
- import java.io.InputStream;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.Properties;
- public class ConnectionProvider {
- private static final String DB_PROPS_PATH = "/db/db.properties";
- private String driver;
- private String url;
- private String username;
- private String password;
- private Connection jdbcConnection;
- public static ConnectionProvider instance;
- public ConnectionProvider() throws SQLException {
- Properties properties = new Properties();
- InputStream inputStream = ClassLoader.class.getResourceAsStream(DB_PROPS_PATH);
- try {
- if (inputStream != null) {
- properties.load(inputStream);
- inputStream.close();
- }
- } catch (IOException exception) {
- exception.printStackTrace();
- }
- driver = properties.getProperty("db.driver");
- url = properties.getProperty("db.url");
- username = properties.getProperty("db.username");
- password = properties.getProperty("db.password");
- try {
- Class.forName("org.h2.Driver");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- this.connect();
- }
- public String getValue () {
- return url;
- }
- public Connection getConnection() throws SQLException {
- return jdbcConnection;
- }
- public void connect() throws SQLException {
- if (jdbcConnection == null || jdbcConnection.isClosed()) {
- jdbcConnection = DriverManager.getConnection(
- url, username, password);
- }
- }
- public void disconnect() throws SQLException {
- if (jdbcConnection != null && !jdbcConnection.isClosed()) {
- jdbcConnection.close();
- }
- }
- public static ConnectionProvider getInstance() throws SQLException {
- if (instance == null) {
- instance = new ConnectionProvider();
- }
- return instance;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement