Skip to content

Instantly share code, notes, and snippets.

@ThomRoman
Created July 23, 2019 05:54
Show Gist options
  • Save ThomRoman/c5f7f0c4f1b71ffd974c8c5f16839406 to your computer and use it in GitHub Desktop.
Save ThomRoman/c5f7f0c4f1b71ffd974c8c5f16839406 to your computer and use it in GitHub Desktop.
Singleton java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.shoppingcar.model.dao.postgres;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author Thom
*/
public class PSQLConnection {
private static PSQLConnection instance;
private final String url = "";
private final String username = "";
private final String password = "";
private Connection cn;
private PSQLConnection() throws SQLException {
try {
Class.forName("org.postgresql.Driver");
this.cn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException ex) {
System.out.println("Error connection "+ex);
}
}
public synchronized static PSQLConnection getConnection() throws SQLException {
if (instance == null || instance.getCon().isClosed()) {
instance = new PSQLConnection();
}
return instance;
}
public static void closeConnection(ResultSet res, PreparedStatement prep) {
try {
if (instance != null){
instance.getCon().close();
instance=null;
}
if (res != null) res.close();
if (prep != null) prep.close();
} catch (SQLException ex) {
System.out.println("Error close connection "+ex);
}
}
private Connection getCon(){
return cn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment