Advertisement
Guest User

Untitled

a guest
Mar 29th, 2020
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1.  
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import java.util.*;
  6.  
  7. public class DriverManagerConnectionPool  {
  8.  
  9.     static {
  10.         freeDbConnections = new ArrayList<Connection>();
  11.         try {
  12.             Class.forName("com.mysql.cj.jdbc.Driver");
  13.         } catch (ClassNotFoundException e) {
  14.             e.getStackTrace();
  15.         }
  16.     }
  17.    
  18.     private static synchronized Connection createDBConnection() throws SQLException {
  19.  
  20.         String url = "jdbc:postgresql://localhost/test";
  21.         Properties props = new Properties();
  22.         props.setProperty("user","fred");
  23.         props.setProperty("password","secret");
  24.         props.setProperty("ssl","true");
  25.         Connection conn = DriverManager.getConnection(url, props);
  26.  
  27.  
  28.  
  29.         newConnection.setAutoCommit(false);
  30.         return newConnection;
  31.     }
  32.  
  33.     public static synchronized Connection getConnection() throws SQLException {
  34.         Connection connection;
  35.  
  36.         if (!freeDbConnections.isEmpty()) {
  37.             connection = (Connection) freeDbConnections.get(0);
  38.             freeDbConnections.remove(0);
  39.  
  40.             try {
  41.                 if (connection.isClosed())
  42.                     connection = getConnection();
  43.             } catch (SQLException e) {
  44.                 connection.close();
  45.                 connection = getConnection();
  46.             }
  47.         } else {
  48.             connection = createDBConnection();     
  49.         }
  50.  
  51.         return connection;
  52.     }
  53.  
  54.     public static synchronized void releaseConnection(Connection connection) throws SQLException {
  55.         if(connection != null) freeDbConnections.add(connection);
  56.     }
  57.    
  58.    
  59.     private static List<Connection> freeDbConnections;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement