title: How to properly close datasource connection?
body: <p>I have this class but Im not sure on how to properly close connection because Im still having this error even though I only have 3 users logged in but with multiple sql queries.</p>
  
  <blockquote>
  <pre><code>&gt; com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
  &gt; Data source rejected establishment of connection,  message from
  &gt; server: "Too many connections"
  </code></pre>
  </blockquote>
  
  <pre><code>import java.io.File;
  import java.io.IOException;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;
  import java.text.DateFormat;
  import java.text.SimpleDateFormat;
  import java.util.ArrayList;
  import java.util.Date;
  import java.util.List;
  
  import javax.sql.DataSource;
  
  public class UserDaoImpl implements UserDao
  {
  
      DataSource dataSource;
  
      public DataSource getDataSource()
      {
              return this.dataSource;
      }
  
      public void setDataSource(DataSource dataSource)
      {
              this.dataSource = dataSource;
      }
  
  
      public boolean isValidUser(String username, String password) throws SQLException
      {       
          PreparedStatement pstmt = null;
          ResultSet resultSet = null;
          boolean rt = false;
          try{
              PasswordEncryptor pws = new PasswordEncryptor();
              String encryptedPass = pws.encrypt(password);
  
              String query = "Select count(1) from userdetails where username = ? and password = ?";
              pstmt = dataSource.getConnection().prepareStatement(query);
              pstmt.setString(1, username);
              pstmt.setString(2, encryptedPass);
              resultSet = pstmt.executeQuery();
              if (resultSet.next()){
                      rt =  (resultSet.getInt(1) &gt; 0);
              }
              else{
                  rt = false;
              }
      }
      catch(Exception e){
          e.printStackTrace();
  
      }
      finally{
          resultSet.close();
          pstmt.close();
          dataSource.getConnection().close();
      }
  
          return rt;  
      }
  }
  </code></pre>
  
  <p>SpringConfiguration.xml</p>
  
  <pre><code>    &lt;bean name="userDao" class="com.spring.acadconnect.services.UserDaoImpl"&gt;
     &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt;
     &lt;/bean&gt;
  
  &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
  
      &lt;property name="driverClassName" value="com.mysql.jdbc.Driver" /&gt;
  
      &lt;property name="url" value="jdbc:mysql://localhost:3306/acadconnect" /&gt;
  
      &lt;property name="username" value="root" /&gt;
  
      &lt;property name="password" value="" /&gt;
  
  &lt;/bean&gt;
  </code></pre>