Advertisement
Guest User

Untitled

a guest
May 23rd, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1. package com.sm.data;
  2.  
  3. import java.sql.CallableStatement;
  4. import java.sql.Connection;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import java.sql.Wrapper;
  9. import javax.naming.Context;
  10.  
  11. import javax.naming.InitialContext;
  12. import javax.naming.NamingException;
  13. import javax.sql.DataSource;
  14.  
  15. public class DBPool {
  16.  
  17.     static Connection connection = null;
  18.  
  19.     static {
  20.  
  21.         try {
  22.             Context context = new InitialContext();
  23.             if (context == null) {
  24.                 throw new Exception("Uh oh -- no context!");
  25.             }
  26.  
  27.             DataSource ds = (DataSource) context.lookup("java:/comp/env/jdbc/PineappleDB");
  28.  
  29.             if (ds == null) {
  30.                 throw new Exception("Data Source not found!");
  31.             }
  32.             connection = ds.getConnection();
  33.  
  34.         } catch (NamingException | SQLException e) {
  35.             e.printStackTrace();
  36.         } catch (Exception e) {
  37.             e.printStackTrace();
  38.         }
  39.     }
  40.  
  41.     public static Connection getConnection() {
  42.         return connection;
  43.     }
  44.  
  45.     public static Connection validConnection(Connection conn) throws SQLException {
  46.         if (conn == null || conn.isClosed()) {
  47.             conn = DBPool.getConnection();
  48.         }
  49.  
  50.         return conn;
  51.     }
  52.  
  53.     public static void slaughter(Wrapper... obj) {
  54.         for (Wrapper o : obj) {
  55.             try {
  56.                 if (o != null) {
  57.                     if (o instanceof Connection) {
  58.                         ((Connection) o).close();
  59.                     } else if (o instanceof CallableStatement) {
  60.                         ((CallableStatement) o).close();
  61.                     } else if (o instanceof Statement) {
  62.                         ((Statement) o).close();
  63.                     } else if (o instanceof ResultSet) {
  64.                         ((ResultSet) o).close();
  65.                     }
  66.                 }
  67.             } catch (SQLException e) {
  68.             } finally {
  69.                 o = null;
  70.             }
  71.         }
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement