spring Jdbctemplate返回插入记录的自增Id

来源:互联网 发布:铵明矾用来乎肚子好么 编辑:程序博客网 时间:2024/04/29 22:16

通常情况下我们在程序中往数据库插入记录,如果主键id是由数据库负责生成,在插入成功之后都是返回主键id方便在插入其它数据时做主键关联,spring Jdbctemplate对这个也是支持的,主要代码如下:

public int insertTable(LabelForm f) throws SQLException,ParseException{    String content = f.getSiteId();    final String sql = "insert into TAG_INFO(SITE_ID,NAME,CONTENT) values(?,?,'"+content+"')";    KeyHolder keyHolder = new GeneratedKeyHolder();    getJdbcTemplate().update(            new PreparedStatementCreator() {                public PreparedStatement createPreparedStatement(Connection con) throws SQLException                {                    PreparedStatement ps = getJdbcTemplate().getDataSource()                            .getConnection().prepareStatement(sql,new String[]{ "SITE_ID" ,"NAME"});                    ps.setString(1, "站点号");                    ps.setString(2, "我的名字");                    return ps;                }            }, keyHolder);    System.out.println("自动插入id============================" + keyHolder.getKey().intValue());    return keyHolder.getKey().intValue();}


0 0
原创粉丝点击