您好我正在尝试从我的数据库获取所有值并将它们存储到列表中。 每行值都放入一个对象中,然后存储在一个列表中。
我应该如何使用准备好的声明或声明?
这是我当前的伪代码
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);
}
答案 0 :(得分:0)
首先获得ResultSet
ResultSet rset = st.executeQuery();
然后
while(rset.next()){
答案 1 :(得分:0)
一般来说:
要管理这些资源,java 6和java 7之间存在一些差异。
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();
}
}
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);
}
}
}
注意:我没有管理连接,因为它通常在应用程序开始结束时打开和关闭。
注意:钻石&lt;&gt; java 7方式