主题:ArrayList声明问题
程序如下 如果把ArrayList的声明写在while外面 返回的时候能得到所有人的信息 也就是说数据库里所有人的信息都存到ArrayList声明的al中了
public ArrayList getAllPersonInfm()
{
[color=FF0000] ArrayList al = new ArrayList();[/color]
try
{
//得到链接
conn = DBToolss.getConnection();
//得到statement
state = conn.createStatement();
String sql = "select * from stuperson";
rs = state.executeQuery(sql);
while(rs.next())
{
Person p =new Person();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setAddress(rs.getString("address"));
al.add(p);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
DBToolss.closeRs(rs);
DBToolss.closeState(state);
DBToolss.closeConn(conn);
}
return al;
}
要是按下面这个写法,al在while中声明 为什么只返回一个数据信息呢?
public ArrayList getAllPersonInfm()
{
ArrayList al = null;
try
{
//得到链接
conn = DBToolss.getConnection();
//得到statement
state = conn.createStatement();
String sql = "select * from stuperson";
rs = state.executeQuery(sql);
while(rs.next())
{
[color=000080]al = new ArrayList();[/color]
Person p =new Person();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setAddress(rs.getString("address"));
al.add(p);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
DBToolss.closeRs(rs);
DBToolss.closeState(state);
DBToolss.closeConn(conn);
}
return al;
}
public ArrayList getAllPersonInfm()
{
[color=FF0000] ArrayList al = new ArrayList();[/color]
try
{
//得到链接
conn = DBToolss.getConnection();
//得到statement
state = conn.createStatement();
String sql = "select * from stuperson";
rs = state.executeQuery(sql);
while(rs.next())
{
Person p =new Person();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setAddress(rs.getString("address"));
al.add(p);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
DBToolss.closeRs(rs);
DBToolss.closeState(state);
DBToolss.closeConn(conn);
}
return al;
}
要是按下面这个写法,al在while中声明 为什么只返回一个数据信息呢?
public ArrayList getAllPersonInfm()
{
ArrayList al = null;
try
{
//得到链接
conn = DBToolss.getConnection();
//得到statement
state = conn.createStatement();
String sql = "select * from stuperson";
rs = state.executeQuery(sql);
while(rs.next())
{
[color=000080]al = new ArrayList();[/color]
Person p =new Person();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setAddress(rs.getString("address"));
al.add(p);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
DBToolss.closeRs(rs);
DBToolss.closeState(state);
DBToolss.closeConn(conn);
}
return al;
}