Spring 对JDBC的支持

2019-03-06  本文已影响0人  蚁丶点

第九讲

1. JdbcTemplate是用来对数据库进行操作(增删改查)的工具类

XML配置如下是

2.增删改查应用

public class StudentDaoImpl implements StudentDao{

private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

this.jdbcTemplate = jdbcTemplate;

}

@Override

public int addStudent(Student student) {

String sql="insert into t_student values(null,?,?)";

Object []params=new Object[]{student.getName(),student.getAge()};

return jdbcTemplate.update(sql,params);

}

@Override

public int updateStudent(Student student) {

String sql="update t_student set name=?,age=? where id=?";

Object []params=new Object[]{student.getName(),student.getAge(),student.getId()};

return jdbcTemplate.update(sql,params);

}

@Override

public int deleteStudent(int id) {

String sql="delete from t_student where id=?";

Object []params=new Object[]{id};

return jdbcTemplate.update(sql,params);

}

@Override

public List<Student> findStudents() {

String sql="select * from t_student";

final List<Student> studentList=new ArrayList<Student>();

jdbcTemplate.query(sql, new RowCallbackHandler(){

@Override

public void processRow(ResultSet rs) throws SQLException {

Student student=new Student();

student.setId(rs.getInt("id"));

student.setName(rs.getString("name"));

student.setAge(rs.getInt("age"));

studentList.add(student);

}

});

return studentList;

}

}

上一篇下一篇

猜你喜欢

热点阅读