首页 > 代码库 > 数据库课设(一)

数据库课设(一)

  • 先看出错的代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public List getDeptInfo(){
String sql = "select * from department";
PreparedStatement psmt=null;
List list = new ArrayList();
try {
psmt = conn.prepareStatement(sql);
ResultSet rs = psmt.executeQuery();
Department dept = null;
while(rs.next()){
dept.setDeptId(rs.getInt("DeptId"));
dept.setDeptName(rs.getString("DeptName"));
list.add(dept);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}

做数据库课设,有段逻辑代码是通用的,在好几个了业务中用同样的思路来处理,可是一直报空指针错误!调试也没看出来错误。后来才发现问题出在while(rs.next())里面。

1
2
3
因为每一次循环都要把dept放到list里面,也就是list.add(dept);
所以每次循环开始都要新实例化一个dept,dept = new Department();这样就不会报空指针错误了。
  • 正确的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public List getDeptInfo(){
String sql = "select * from department";
PreparedStatement psmt=null;
List list = new ArrayList();
try {
psmt = conn.prepareStatement(sql);
ResultSet rs = psmt.executeQuery();
Department dept;
while(rs.next()){
dept = new Department();
dept.setDeptId(rs.getInt("DeptId"));
dept.setDeptName(rs.getString("DeptName"));
list.add(dept);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}

数据库课设(一)