title: How should I use try-with-resources with JDBC?
body: <p>I have a method for getting users from a database with JDBC:</p>
  
  <pre><code>public List&lt;User&gt; getUser(int userId) {
      String sql = "SELECT id, name FROM users WHERE id = ?";
      List&lt;User&gt; users = new ArrayList&lt;User&gt;();
      try {
          Connection con = DriverManager.getConnection(myConnectionURL);
          PreparedStatement ps = con.prepareStatement(sql); 
          ps.setInt(1, userId);
          ResultSet rs = ps.executeQuery();
          while(rs.next()) {
              users.add(new User(rs.getInt("id"), rs.getString("name")));
          }
          rs.close();
          ps.close();
          con.close();
      } catch (SQLException e) {
          e.printStackTrace();
      }
      return users;
  }
  </code></pre>
  
  <p>How should I use Java 7 <a href="http://download.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" rel="noreferrer"><strong>try-with-resources</strong></a> to improve this code?</p>
  
  <p>I have tried with the code below, but it uses many <code>try</code> blocks, and doesn't improve the <strong>readability</strong> much. Should I use <code>try-with-resources</code> in another way?</p>
  
  <pre><code>public List&lt;User&gt; getUser(int userId) {
      String sql = "SELECT id, name FROM users WHERE id = ?";
      List&lt;User&gt; users = new ArrayList&lt;&gt;();
      try {
          try (Connection con = DriverManager.getConnection(myConnectionURL);
               PreparedStatement ps = con.prepareStatement(sql);) {
              ps.setInt(1, userId);
              try (ResultSet rs = ps.executeQuery();) {
                  while(rs.next()) {
                      users.add(new User(rs.getInt("id"), rs.getString("name")));
                  }
              }
          }
      } catch (SQLException e) {
          e.printStackTrace();
      }
      return users;
  }
  </code></pre>