title: Proper usage of JDBC Connection Pool (Glassfish)
body: <p>I need a database connection in Java Web service implemented as a session bean, and I'm not sure if I do it right. </p>
  
  <p>I created a class </p>
  
  <pre><code>public final class SQLUtils   {  
      //.....  
      private static DataSource  m_ds=null;    
  
      static  
      {  
          try
          {
              InitialContext ic = new InitialContext();
              m_ds = (DataSource) ic.lookup(dbName); //Connection pool and jdbc resource previously created in Glassfish  , dbName contains the proper JNDI resource name 
  
          }
          catch (Exception e)
          {
              e.printStackTrace();
              m_ds = null;
          }
  
      }
  
      public static Connection getSQLConnection() throws SQLException  
      {  
          return m_ds.getConnection();             
      }
  }
  </code></pre>
  
  <p>Whenever I need a connection I do </p>
  
  <pre><code> Connection cn = null;  
   try  
   {
       cn = SQLUtils.getSQLConnection();
       // use connection
   }
   finally 
   {
       if (null != cn)
       {
           try
           {
               cn.close();
           }
           catch (SQLException e)
           {
  
           }
       }
   }
  </code></pre>
  
  <p>Is it ok to use it this way, or I DataSource must be a member of the bean ?</p>
  
  <pre><code>  @Stateless  
    @WebService  
    public class TestBean  {  
     private @Resource(name=dbName) DataSource m_ds;   
    }  
  </code></pre>
  
  <p>I'm sorry if it is a nube question, but I'm pretty new to Java. Thanks in advance.</p>