public class DefaultTemplate {
private JdbcTemplate jt;
public void insert(Person person) {
String sql = "INSERT INTO person(name,password) VALUES (?,?)";
// 全部的值应该变为对象数组
Object params[] = new Object[] { person.getName(), person.getPassword() };
int type[] = new int[] { Types.VARCHAR, Types.VARCHAR };
jt.update(sql, params, type);
}
public void update(Person person) {
String sql = "UPDATE person SET name=?,password=? WHERE id=?";
Object params[] = new Object[] { person.getName(),
person.getPassword(), new Integer(person.getId()) };
int type[] = new int[] { Types.VARCHAR, Types.VARCHAR, Types.INTEGER };
jt.update(sql, params, type);
}
public Person getPerson(int id) {
final Person per = new Person();
String sql = "SELECT id,name,password FROM person WHERE id=?";
Object[] params = new Object[] { new Integer(id) };
//RowCallbackHandler是接口
jt.query(sql, params, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
per.setId(rs.getInt(1));
per.setName(rs.getString(2));
per.setPassword(rs.getString(3));
}
});
return per;
}
public int getCount() {
final Person per = new Person() ;
String sql = "SELECT COUNT(id) FROM person";
Object[] params = new Object[] {};
jt.query(sql, params, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
per.setCount(rs.getInt(1)) ;
}
});
return per.getCount();
}
public List queryAll() {
final List<Person> all = new ArrayList<Person>();
String sql = "SELECT id,name,password FROM person";
Object[] params = new Object[] {};
jt.query(sql, params, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
Person per = new Person();
per.setId(rs.getInt(1));
per.setName(rs.getString(2));
per.setPassword(rs.getString(3));
all.add(per);
}
});
return all;
}
public void delete(int id) {
String sql = "DELETE FROM person WHERE id=?";
Object params[] = new Object[] { new Integer(id) };
int type[] = new int[] { Types.INTEGER };
jt.update(sql, params, type);
}
public JdbcTemplate getJt() {
return jt;
}
public void setJt(JdbcTemplate jt) {
this.jt = jt;
}
springjdbc
最新推荐文章于 2014-07-02 17:22:40 发布