Skip to content

Instantly share code, notes, and snippets.

@anupammaiti
Forked from jasoet/gist:3843797
Created November 24, 2020 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anupammaiti/965fc51d5ab79dd9b5a017c29e265adf to your computer and use it in GitHub Desktop.
Save anupammaiti/965fc51d5ab79dd9b5a017c29e265adf to your computer and use it in GitHub Desktop.
Database Connection Singleton
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.secondstack.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author Deny Prasetyo
*/
public class DatabaseConnection {
private static DatabaseConnection instance;
private Connection connection;
private String url = "jdbc:postgresql://localhost:5432/jdbc";
private String username = "root";
private String password = "localhost";
private DatabaseConnection() throws SQLException {
try {
Class.forName("org.postgresql.Driver");
this.connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException ex) {
System.out.println("Database Connection Creation Failed : " + ex.getMessage());
}
}
public Connection getConnection() {
return connection;
}
public static DatabaseConnection getInstance() throws SQLException {
if (instance == null) {
instance = new DatabaseConnection();
} else if (instance.getConnection().isClosed()) {
instance = new DatabaseConnection();
}
return instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment