一、批量删除
通过一个循环来遍历要删除的用户信息的ID数组,然后依次调用单个删除信息的方法来删除每一个用户信息。
批量删除可以减少数据库的负担,因为在一次连接数据库的过程中,可以同时删除多条数据,而不需要多次连接数据库。
二、代码实现
1.连接数据库,使用删除语句实现信息删除方法
/**
* 通过id查教师信息
*/
@Override
public Teacher findTeacherById(int id) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Teacher teacher = null;
conn = DButils.getConnection();//连接数据库
String sql = "SELECT id,name,password,gender,email,remark,activatecode,state FROM teacher WHERE id=?";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1,id);
rs = ps.executeQuery();
while (rs.next()){
teacher = new Teacher();
teacher.setId(rs.getInt(1));
teacher.setName(rs.getString(2));
teacher.setPassword(rs.getString(3));
teacher.setGender(rs.getString(4));
teacher.setEmail(rs.getString(5));
teacher.setRemark(rs.getString(6));
teacher.setActivatecode(rs.getString(7));
teacher.setState(rs.getString(8));
}
} catch (SQLException e) {
e.printStackTrace();
}
DButils.closeDB(conn,ps,rs);
return teacher;
}
/**
* 删除教师数据
*/
@Override
public boolean deleteTeacherById(int id) {
Connection conn = null;
String sql = null;
PreparedStatement ps =null;
int i=0;
boolean flag = false;
try{
conn = DButils.getConnection();
sql="DELETE FROM teacher WHERE id=?";
ps = conn.prepareStatement(sql);
ps.setInt(1,id);
i=ps.executeUpdate();
if (i>0){
flag=true;
}
}catch (SQLException e){
e.printStackTrace();
}
DButils.closeDB(conn,ps,null);
return flag;
}
2.对教师id和删除状态进行封装并对两个方法进行处理
public class StateInfor {
private int stateId;
private String teacherId;
public int getStateId() {
return stateId;
}
public void setStateId(int stateId) {
this.stateId = stateId;
}
public String getTeacherId() {
return teacherId;
}
public void setTeacherId(String teacherId) {
this.teacherId = teacherId;
}
}
/**
* 批量删除
*/
@Override
public StateInfor batchesDelete(String[] ids) {
TeacherDao teacherDao = new TeacherDaoImpl();
StateInfor stateInfor = new StateInfor();
for (String id : ids){
Teacher teacher = teacherDao.findTeacherById(Integer.parseInt(id));
if (teacher==null){
stateInfor.setStateId(0);//为0时未选择数据
stateInfor.setTeacherId(id);
return stateInfor;
}
}
for (String id : ids){
boolean b = teacherDao.deleteTeacherById(Integer.parseInt(id));
if (b==false){
stateInfor.setStateId(1);//为1时删除失败
stateInfor.setTeacherId(id);
return stateInfor;
}
}
stateInfor.setStateId(2);//为2时删除成功
return stateInfor;
}
3.对前台网页进行处理
//使用form表单上传数据