Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.*;
- public class DriverManagerConnectionPool {
- static {
- freeDbConnections = new ArrayList<Connection>();
- try {
- Class.forName("com.mysql.cj.jdbc.Driver");
- } catch (ClassNotFoundException e) {
- e.getStackTrace();
- }
- }
- private static synchronized Connection createDBConnection() throws SQLException {
- String url = "jdbc:postgresql://localhost/test";
- Properties props = new Properties();
- props.setProperty("user","fred");
- props.setProperty("password","secret");
- props.setProperty("ssl","true");
- Connection conn = DriverManager.getConnection(url, props);
- newConnection.setAutoCommit(false);
- return newConnection;
- }
- public static synchronized Connection getConnection() throws SQLException {
- Connection connection;
- if (!freeDbConnections.isEmpty()) {
- connection = (Connection) freeDbConnections.get(0);
- freeDbConnections.remove(0);
- try {
- if (connection.isClosed())
- connection = getConnection();
- } catch (SQLException e) {
- connection.close();
- connection = getConnection();
- }
- } else {
- connection = createDBConnection();
- }
- return connection;
- }
- public static synchronized void releaseConnection(Connection connection) throws SQLException {
- if(connection != null) freeDbConnections.add(connection);
- }
- private static List<Connection> freeDbConnections;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement