Spring JdbcTemplate实现update或insert

tangxiong0 2010-06-04

三种使用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;

     }

}

Spring JdbcTemplate实现update或insert);

第二种方式,重载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);

        }

});

Spring JdbcTemplate实现update或insert

Spring JdbcTemplate实现update或insert//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;

}

});

}

相关推荐

Gbug00 / 0评论 2010-10-08