日期:2014-05-16 浏览次数:20518 次
三种使用Spring JdbcTemplate实现update或insert操作
?
?
第一种方式,重载PreparedStatementCreator
jdbcTemplate.update(new PreparedStatementCreator(){
????public PreparedStatement createPreparedStatement(Connection conn){
???????? String sql="insert into user (name,age) values(?,?)";
???????? PreparedStatement ps=con.prepareStatement(sql);
???????? ps.setString(1,name);
???????? ps.setInt(2,age);
????????return ps;
???? }
}
);
第二种方式,重载PreparedStatementSetter
jdbcTemplate.update("insert into user(name,age) values(?,?)",new PreparedStatementSetter(){
??????public void setValues(PreparedStatement ps) throws SQLException {
??????????? ps.setString(1,name);
??????????? ps.setInt(2,age);
??????? }
});
//jdbcTemplate会自动创建PreparedStatementCreator实例,以提供传递给setValues方法的ps对象
第三种方式,直接使用SQL
jdbcTemplate.update("insert into user (name,age) "+"values (' " + name + " ', " +age +")");
?
?
//批量更新
public void insertBooks(List<Book> book)
{
final List<Book> tempBook=book;
String sql="insert into book(name,pbYear) values(?,?)";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter()
{
public void setValues(PreparedStatement ps,int i)throws SQLException
{
String name=tempBook.get(i).getName();
int pbYear=tempBook.get(i).getPbYear();
ps.setString(1, name);
ps.setInt(2, pbYear);
}
public int getBatchSize()
{
return 25;
}
});
}