Spring的JdbcTemplate插入操作返回主键ID的方法

public  Long insertAndGetKey(final String sql, final SmsBean smsbean) {  
    KeyHolder keyHolder = new GeneratedKeyHolder();  
    jdbcTemplate.update(new PreparedStatementCreator() {  
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {  
              
            //String sql_sms = "insert into  sms(title,content,date_s,form,sffs,by1,by2,by3) values (?,?,'"+dates+"',?,?,?,?,?)";   
               PreparedStatement ps = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);  
               ps.setString(1, smsbean.getTitle());  
               ps.setString(2, smsbean.getContent());  
               ps.setString(3, smsbean.getForm());  
               ps.setString(4, smsbean.getSffs());  
               /* 
             * by1 存放的是 草稿主人的ID 
             * 当消息为发送。清楚by1的ID    
             */   
               ps.setString(5, "");  
               ps.setString(6, smsbean.getBy2());  
               ps.setString(7, smsbean.getBy3());  
               return ps;  
        }  
    }, keyHolder);  
      
    Long generatedId = keyHolder.getKey().longValue();   
    return generatedId;  
}  

你可能感兴趣的:(JdbcTemplate)