对于Spring应用,Spring提供了一个更好的数据持久化的框架,Spring让持久层的类UserDao继承org.springframework.jdbc.core.JdbcTemplate这个封装了jdbc操作的类,要建立JdbcTemplate的实例,必须要有一个DataSource物件作为建构时的物件.
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
例子(1):-----取得模版
package onlyfun.caterpillar;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDAO implements IUserDAO {
    private JdbcTemplate jdbcTemplate;
    public void setDataSource(DataSource dataSource) {
        jdbcTemplate = new JdbcTemplate(dataSource);
    }
        return null;
    }
}
例子(2):-----update操作(同样的操作适用于update、insert、delete)
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate
.update(
"UPDATE user SET age = ? WHERE id = ?",
new PreparedStatementSetter() {
public void setValues(PreparedStatementSetter ps)
throws SQLException {
ps.setInt(1, 18);
ps.setString(2, "erica");
}
}
);
第一个用于创建PreparedStatement的SQL。第二个参数是为PreparedStatement设定参数的
PreparedStatementSetter
注意:我们还可以通过JdbcTemplate.call方法调用存储过程.

posted on 2007-05-25 11:16  王永庆  阅读(535)  评论(0编辑  收藏  举报