数据读取问题
数据源配置
<data-sources >
<data-source>
<set-property property="autoCommit" value="true" />
<set-property property="readOnly" value="false" />
<set-property property="description" value="" />
<set-property property="driverClass" value="com.mysql.jdbc.Driver" />
<set-property property="minCount" value="1" />
<set-property property="loginTimeout" value="1000" />
<set-property property="password" value="******" />
<set-property property="user" value="root" />
<set-property property="maxCount" value="10" />
<set-property property="url" value="jdbc:mysql://localhost:3306/struts" />
</data-source>
</data-sources>
Action代码:
//取出数据源
DataSource ds = getDataSource(request);
//取出数据库连接
Connection con = ds.getConnection();
//查询留言人
Post p=new Post();
List<Post> list = new ArrayList<Post>();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT id,name FROM post ORDER BY id");
while (rs.next()) {
//读出 name 保存到 ArrayList 里面
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
list.add(p);
}
System.out.println(list);
Iterator iter=list.iterator();
while(iter.hasNext())
{
p=(Post)iter.next();
System.out.println(p.getId()+"\t"+p.getName());
}
rs.close();
st.close();
con.close(); //关闭连接
//保存留言人到request,以便转到jsp页面显示
request.setAttribute("list", list);
return mapping.findForward("success");
}
数据库理由这样四条记录
1 zxcxz
2 zxc
3 www
4 adasdd
为什么读出来的总是:
4 adasdd
4 adasdd
4 adasdd
4 adasdd
------解决方案--------------------while (rs.next()) {
//读出 name 保存到 ArrayList 里面
Post p=new Post();//必须重新分配,否则覆盖原有的对象
p.setId(rs.getInt("id"));