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

如何在JDBC操作SQLite3时获取最后插入记录的id值

问题原因

你之前的尝试存在两个核心错误:

  1. 对SELECT语句调用getUpdateCount()无法拿到查询结果,该方法仅对INSERT/UPDATE/DELETE等更新类操作返回影响行数,查询类语句调用该方法固定返回-1。
  2. 执行SELECT MAX(id) FROM temp时,结果集的列名为聚合函数表达式MAX(id)而非id,直接通过rs.getInt("id")读取自然会报列不存在的错误。

解决方案

方案1:使用JDBC标准获取自动生成键(最推荐)

这是JDBC规范内置的通用方案,不依赖数据库特性,并发场景下也不会出现ID错拿的问题,无需额外执行查询语句。
修改插入逻辑如下:

// 执行插入时指定需要返回自动生成的键
PreparedStatement pstmt = conn.prepareStatement(insertSomethingQuery, Statement.RETURN_GENERATED_KEYS);
pstmt.executeUpdate();
// 读取生成的主键结果集
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
    int lastInsertId = rs.getInt(1);
    System.out.println("The last inserted id is " + lastInsertId);
}

方案2:修正last_insert_rowid()调用方式

你不需要修改SQL,只需要改为从ResultSet中读取结果即可:

Statement stmt = exec("SELECT last_insert_rowid()", conn);
ResultSet rs = stmt.getResultSet();
if (rs.next()) {
    // 按列索引读取(结果集第一列索引为1,而非0)
    int lastInsertId = rs.getInt(1);
    System.out.println("The last inserted id is " + lastInsertId);
}

方案3:修正MAX(id)查询逻辑

有两种修正方式,二选一即可:

// 修正方式1:给聚合列设置别名
ResultSet rs = exec("SELECT MAX(id) AS id FROM temp", conn).getResultSet();
if (rs.next()) {
    int lastInsertId = rs.getInt("id");
    System.out.println("The last inserted id is " + lastInsertId);
}

// 修正方式2:直接按列索引读取
/*
ResultSet rs = exec("SELECT MAX(id) FROM temp", conn).getResultSet();
if (rs.next()) {
    int lastInsertId = rs.getInt(1);
}
*/

注意:该方案在多连接并发插入的场景下可能拿到其他连接插入的ID,仅适合单连接操作的场景使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:24:01