spring mvc 插入一条数据 返回该数据的主键编号

 1 import org.springframework.jdbc.core.PreparedStatementCreator;
 2 import org.springframework.jdbc.support.GeneratedKeyHolder;
 3 import org.springframework.jdbc.support.KeyHolder;
 4 
 5 import java.sql.Connection;
 6 import java.sql.PreparedStatement;
 7 import java.sql.SQLException;
 8 
 9 
10     public int addrole(final Object[] params){
11         
12         KeyHolder keyHolder = new GeneratedKeyHolder();
13         final String sql = "insert into role (rolename,status) values (?,1)";
14         
15         this.jdbcTemplate.update(new PreparedStatementCreator(){
16             public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
17                 PreparedStatement ps = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
18                 for(int i = 0; i < params.length; i++) {
19                     ps.setString(i + 1, params[i].toString());
20                 }
21                 return ps;
22             }
23         }, keyHolder);
24         return keyHolder.getKey().intValue();
25     }
原文地址:https://www.cnblogs.com/zfy0098/p/5107541.html