Connection con = null;
PreparedStatement statement = null;
ResultSet res = null;
List<Student> students = new ArrayList<Student>();
List<Student> getAll() {
try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); statement = (PreparedStatement) con.createStatement(); res = statement.executeQuery("SELECT * FROM students"); } catch (Exception e) { e.printStackTrace(); } try { while(res.next()){ String name = res.getString(1); int age = res.getInt(2);
Student student = new Student(name,age); students.add(student); } } catch (SQLException e1) { e1.printStackTrace(); } if (res != null) { try { res.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } return students; }