-
-
Save athulmurali/6c0f1d1bfd7b08069ae9a2a8fbcb30d1 to your computer and use it in GitHub Desktop.
Database Connection Singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 | |
* @modified by : Athul Muralidharan | |
(replaced postgres with mysql ) | |
*/ | |
public class DatabaseConnection { | |
private static DatabaseConnection instance; | |
private Connection connection; | |
private static DatabaseConnection instance; | |
private Connection connection; | |
private static final String DRIVER = "com.mysql.jdbc.Driver"; | |
private static final String USER = System.getenv("DB_USERNAME"); | |
private static final String PASSWORD = System.getenv("DB_PASSWORD"); | |
private static final String SCHEMA = System.getenv("DB_SCHEMA"); | |
private static final String DB_HOSTNAME = System.getenv("DB_HOSTNAME"); | |
private static final String URL = String.format("jdbc:mysql://%s/%s", DB_HOSTNAME, SCHEMA); | |
private DatabaseConnection() throws SQLException { | |
try { | |
Class.forName(DRIVER); | |
this.connection = DriverManager.getConnection(URL, USER, 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