通常情况下我们在程序中往数据库插入记录,如果主键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(); }