You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在JDBC中获取插入数据时自动生成ID的技术咨询

获取Oracle自增Identity字段值的JDBC实现方案

嘿,针对你要获取插入后自动生成的person_id的需求,这里有两种靠谱的JDBC实现方案,还能解决你当前代码里的SQL注入风险:

方法1:JDBC标准方式(跨数据库兼容)

这是JDBC规范提供的通用方法,不需要依赖数据库特定语法,适合需要跨数据库的场景:

String insertSql = "insert into PERSON (firstname, lastname) values (?, ?)";
// 注意第二个参数:Statement.RETURN_GENERATED_KEYS,告诉JDBC要返回生成的主键
try (PreparedStatement pstmt = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS)) {
    pstmt.setString(1, firstname);
    pstmt.setString(2, lastname);
    int affectedRows = pstmt.executeUpdate();
    
    // 确认插入成功后再获取主键
    if (affectedRows > 0) {
        try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
            if (generatedKeys.next()) {
                int personId = generatedKeys.getInt(1);
                // 这里拿到了自动生成的person_id,按需使用即可
                System.out.println("新插入记录的person_id是: " + personId);
            }
        }
    }
} catch (SQLException e) {
    // 实际项目里建议做更友好的异常处理,比如日志记录
    e.printStackTrace();
}

方法2:Oracle专属RETURNING子句(更灵活)

如果你的代码只针对Oracle数据库,可以用Oracle的RETURNING子句,它支持返回多个生成的字段,用法更直接:

String insertSql = "insert into PERSON (firstname, lastname) values (?, ?) returning person_id into ?";
try (PreparedStatement pstmt = connection.prepareStatement(insertSql)) {
    pstmt.setString(1, firstname);
    pstmt.setString(2, lastname);
    // 注册输出参数,类型要和person_id的number(5)匹配
    pstmt.registerOutParameter(3, Types.INTEGER);
    
    pstmt.executeUpdate();
    
    // 直接从输出参数获取生成的person_id
    int personId = pstmt.getInt(3);
    System.out.println("新插入记录的person_id是: " + personId);
} catch (SQLException e) {
    e.printStackTrace();
}

额外提醒

  • 尽量用PreparedStatement代替你原来的Statement,不仅能避免SQL注入攻击,代码也更易维护和调试
  • 你的建表语句最后多了个多余的逗号,正确的语句应该是:
    create table person ( 
        person_id number(5) generated always as identity 
            minvalue 1 maxvalue 99999 increment by 1 start with 1 cycle cache 10, 
        firstname varchar(10) not null, 
        lastname varchar(10) not null 
    );
    
  • 实际项目中,记得合理处理SQLException,不要只打印堆栈信息,建议结合日志框架记录异常详情

内容的提问来源于stack exchange,提问作者ac_nook

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:13:08