您好,我正在尝试从数据库中获取所有值并将它们存储到列表中。 每行值都放入一个对象中,然后存储在一个列表中。
我应该如何使用准备好的语句或语句来执行此操作?
这是我当前的伪代码
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);
}
}
}
注意:我没有管理连接,因为它在应用程序启动结束时正常打开和关闭。
注意:钻石<> java 7 way
关于java - 准备好的语句从数据库填充列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21490733/