packagedao;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.ArrayList;importjava.util.List;importbean.Student;importutil.DBUtil;public classStudentDaoImpl {public voidaddStudent(Student student)
{
Connection connection=DBUtil.getConnection();
String sql= "insert into student (stuId,stuName) values (?,?)";
PreparedStatement preparedStatement= null;try{
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1,student.getStuId());
preparedStatement.setString(2, student.getStuName());
preparedStatement.executeUpdate();
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(preparedStatement);
DBUtil.close(connection);
}
}public voiddeleteStudent(String stuId) {
Connection connection=DBUtil.getConnection();
String sql= "delete from student where stuId= ?";
PreparedStatement preparedStatement= null;try{
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1, stuId);
preparedStatement.executeUpdate();
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(preparedStatement);
DBUtil.close(connection);
}
}public voidupdateStudent(Student student) {
Connection connection=DBUtil.getConnection();
String sql= "update student set stuName = ? where stuId=?";
PreparedStatement preparedStatement= null;try{
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1, student.getStuName());
preparedStatement.setString(2, student.getStuId());
preparedStatement.executeUpdate();
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(preparedStatement);
DBUtil.close(connection);
}
}public ListloadStudent() {
Connection connection=DBUtil.getConnection();
String sql= "select * from student";
PreparedStatement preparedStatement= null;
ResultSet resultSet=null;
Student student= null;
List students=new ArrayList<>();try{
preparedStatement=connection.prepareStatement(sql);//preparedStatement.setInt(1, id);
resultSet=preparedStatement.executeQuery();while(resultSet.next())
{
student=newStudent();
student.setStuId(resultSet.getString("stuId"));
student.setStuName(resultSet.getString("stuName"));
students.add(student);
}
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(resultSet);
DBUtil.close(preparedStatement);
DBUtil.close(connection);
}returnstudents;
}
}