嗨,我正在尝试从数据库中获取所有值,并将它们存储到列表中。每行值都放入一个对象中,然后存储在列表中。我应该使用准备好的语句还是语句来执行此操作?这是我当前的伪代码 Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, username, password); PreparedStatement st = connection.prepareStatement("SELECT * FROM People"); List People = new List(); while (st.next()) { Person newPerson = new Person(); newPerson.firstName = rset.getString("first_name"); newPerson.lastName = rset.getString("last_name"); newPerson.email = rset.getString("email"); People.add(newPerson); } 最佳答案 一般来说:应用程序启动->打开连接在某些方法上公开陈述和影响结果集关闭stmt(或重新使用它)并关闭结果集(如果错误关闭)应用程序停止->关闭连接要管理这些资源,Java 6和Java 7之间存在一些差异。Java 6 Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, usr, pwd); //..... PreparedStatement st=null; ResultSet rset=null; try { st = connection .prepareStatement("SELECT first_name,last_name,email FROM People"); List<Person> peoples = new ArrayList<Person>(); rset = st.executeQuery(); while (rset.next()) { Person newPerson = new Person(); newPerson.firstName = rset.getString("first_name"); newPerson.lastName = rset.getString("last_name"); newPerson.email = rset.getString("email"); peoples.add(newPerson); } } finally { try { rset.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { st.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }Java 7 Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("", "", ""); //..... try (PreparedStatement st = connection .prepareStatement("SELECT first_name,last_name,email FROM People")) { List<Person> peoples = new ArrayList<>(); // but should be new ArrayList<Person>(); try (ResultSet rset = st.executeQuery()) { while (rset.next()) { Person newPerson = new Person(); newPerson.firstName = rset.getString("first_name"); newPerson.lastName = rset.getString("last_name"); newPerson.email = rset.getString("email"); peoples.add(newPerson); } } }注意:我没有管理连接,因为它在应用程序启动结束时通常是打开和关闭的。注意:diamond java 7的方式 07-27 21:47