一般 JDBC:
int id = 0; String sql = "INSERT INTO ..........."; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try{ con = DriverManager.getConnection(Constant.DB_MAIN); pstmt = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); pstmt.executeUpdate(); ResultSet generatedKeys = pstmt.getGeneratedKeys(); if (generatedKeys.next()){ id = generatedKeys.getInt(1); } }catch (Exception e) { e.printStackTrace(); } finally { ConControl.freeConnection(rs, pstmt, con); }
Spring JDBC Template:
public int insertPopularFaq(PopularFaqBean popularFaq) { String sql = "DECLARE @popular_faq_rule_id INT " + "DECLARE @faq_id INT " + "SET @popular_faq_rule_id = ? " + "SET @faq_id = ? " + "INSERT INTO popular_faq(popular_faq_rule_id, faq_id) VALUES(@popular_faq_rule_id, @faq_id)"; KeyHolder keyHolder = new GeneratedKeyHolder(); cs_JdbcTemplate.update((Connection con) -> { PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); int i = 1; pstmt.setInt(i++, popularFaq.getPopularFaqRuleId()); pstmt.setInt(i++, popularFaq.getFaqId()); return pstmt; }, keyHolder); Number key = keyHolder.getKey(); return key.intValue(); }