`

spring jdbcTemplate 实现批量更新操作接口使用

阅读更多
批量更新操作使用如下代码:
public int[] updatePerson(final String[] ids)
	{
		String sql ="update person set address=? where id=?";
		BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter(){
			public void setValues(PreparedStatement ps,int i) throws SQLException{
	           ps.setString(1, "benling.l@gmail.com");
	           ps.setInt(2, Integer.parseInt(ids[i]));
	          }
	          public int getBatchSize(){
	             return ids.length;
	          }
		};
		return this.getJdbcTemplate().batchUpdate(sql, setter);
	}

第二种方法:重载PreparedStatementCreator,请看代码:
public void insertUsers(User ur)
	{
		 this.getJdbcTemplate().update(new PreparedStatementCreator()
		{
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException
			{
				String sql = "insert into user (name,age) values(?,?)";
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setString(1,"");
				ps.setInt(2,0);
				return ps;
			}
		});
	}

第三种方法:直接使用SQL
jdbcTemplate.update("insert into user (name,age) "+"values (' " + name + " ',  " +age +")");
分享到:
评论
2 楼 benlsoft 2008-12-03  
执行插入操作时返回值是void,无返回值类型。
1 楼 junjieshow 2008-12-01  
public void importDBOnThread() {
try {
String insertSql = "insert into attendance_record"
+ "(ic_sign_id,xxcode,xcode,sign_time,auto_flag,class_no,nj_c,late_flag)"
+ "(select i.autoid,j.xxcode,j.xcode,i.sign_time,'1',j.class_no,j.nj_c,"
+ "(select count(d.id) from dm_attendance_time d "
+ "where i.sign_time between convert(datetime ,SUBSTRING(convert(char,i.sign_time,21),0,12)+ convert(char,starttime,108))"
+ "AND convert(datetime ,SUBSTRING(convert(char,i.sign_time,21),0,12)+ convert(char,endtime,108))"
+ "and d.nj_c like '%'+j.nj_c+'%' and d.late_flag='1')"
+ "from dbo.iccard_sign_record i,nf.dbo.x_jbqk j "
+ "where  j.xxcode=I.xxcode and j.ic_no=I.card_id "
+ "and i.autoid>(isnull((select max(ic_sign_id) from attendance_record),0)))";
System.out.println(insertSql);
System.out.println("maxrows:"+jdbcTemplate.getMaxRows());
int i = jdbcTemplate.update(insertSql);
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
}

同样的流程 只不过是我的sql语句长一些 在这里sql语句没有问题 单纯的在数据库 能够执行插入,这里jdbcTemplate也没有问题 因为这个类里其他方法调用jdbcTemplate.queryForList(sql)就能执行查询 但是为什么单纯的插入跟更新就没有反应呢?也不报错!

相关推荐

Global site tag (gtag.js) - Google Analytics