title: What's wrong with my code Data source rejected establishment of connection, message from server: "Too many connections"
body: <p>I am getting this error from the database</p>
  
  <blockquote>
    <p>Data source rejected establishment of connection,  message from
    server: "Too many connections"</p>
  </blockquote>
  
  <p>I am closing my connections properly, I don't know why i am getting this error when my thread pool is only 5 and i think i am closing the connections. Anyone know why.</p>
  
  <p>Below is my code. I have changed a few things to stay anonymous </p>
  
  <pre><code>public class myMain {
  
      public static void main(String[] args) {
          ExecutorService executor = Executors.newFixedThreadPool(5);
          for (int i = 0; i &lt; (569743 / 100); i++) {
              try {
                  MyClass mclass = new MyClass();
                  executor.execute(mclass);
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
          executor.shutdown();
          try {
              executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
          System.out.println("Finished all threads");
      }
  
  }
  </code></pre>
  
  <p>.</p>
  
  <pre><code>public class MyClass implements Runnable {
  
      public MyClass(){
          Class.forName("com.mysql.jdbc.Driver");
          connect = DriverManager.getConnection("jdbc:mysql://localhost/mytable?" + "user=&amp;password=");
      }
  
      public  void run() {
          try {
              String sql = "My select STATEMENT";
              PreparedStatement stmt = connect.prepareStatement(sql);
  
              ResultSet rs = stmt.executeQuery(sql);
              while (rs.next()) {
                  try {
  
                      int id = rs.getInt("movie_id");
                      String title = rs.getString("title");
                      int year = rs.getInt("year");
                      String trailerUrl = rs.getString("trailerUrl");
                      if (trailerUrl == null || (trailerUrl != null &amp;&amp; trailerUrl.length() == 0)) {
                          YoutubeTrailerFetcher youtube = new YoutubeTrailerFetcher(title, year);
                          String trailer = youtube.getVideoId();
  
                          String updateSql = "my UPDATE Statement";
                          Statement updateStm = connect.createStatement();
                          updateStm.executeUpdate(updateSql);
                          updateStm.close();
  
                      }
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
  
              }
              connect.close();
              stmt.close();
              rs.close();
          }catch(Exception e){
              e.printStackTrace();
          }
      }
  
  }
  </code></pre>