spring Jdbctemplate返回插入記錄的自增Id
阿新 • • 發佈:2019-01-01
通常情況下我們在程式中往資料庫插入記錄,如果主鍵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(); }