OwlFocus

Spring批量执行语句

如何使用Spring执行多条sql语句

在Spring中可以使用ScriptUtils工具类,批量执行Sql语句,如批量执行update table1 set status=0, dprice=55 where id in (9600980);insert into table1 (dprice,status) values(46,0),(55,1);这两条语句。

方法

1
2
3
4
5
6
7
8
9
10
11
public void executeSqlScript(Connection connection,StringBuffer sql)throws SQLException{
try {
connection.setAutoCommit(false);//设置为手工提交模式
ScriptUtils.executeSqlScript(connection, new ByteArrayResource(sql.toString().getBytes()));
connection.commit();//提交事务
} catch (SQLException e) {
connection.rollback();
}finally{
connection.close();
}
}