java - SQL:获取新插入行的ID
问题描述
我正在编写一个 API,其目的是将有关囚犯的数据存储在 minecraft bukkit 插件的监狱中。我提供了一种将玩家送进监狱的方法。调用时,会在数据库表中创建一个条目,该表存储所有当前的囚犯。我向该表添加一个新条目,如下所示:
public static void addNewPunishment(UUID playerUUID, int punishmentBlocks, int maxExtensions) {
try (final PreparedStatement ps = DatabaseConnector.getConnection().prepareStatement(
"insert into PRISONERS(UUID, REMAININGBLOCKS, STARTINGBLOCKS, MAXEXTENSIONS) values (?,?,?,?)")) {
ps.setString(1, playerUUID.toString());
ps.setInt(2, punishmentBlocks);
ps.setInt(3, punishmentBlocks);
ps.setInt(4, maxExtensions);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
但是,在实现使用此 API 的方法时,结果表明,返回新插入行的 id 是必需的,但我完全不知道如何获取它。这是我的表的结构:
我需要此列的“id”值,但我可以得到受影响的行数,这并没有真正的帮助......我怎样才能insert into
返回插入行的特定值?
解决方案
您可以按照以下链接中的说明进行操作:
您的代码可能是:
public static void addNewPunishment(UUID playerUUID, int punishmentBlocks, int maxExtensions) {
try (final PreparedStatement ps = DatabaseConnector.getConnection().prepareStatement(
"insert into PRISONERS(UUID, REMAININGBLOCKS, STARTINGBLOCKS, MAXEXTENSIONS) values (?,?,?,?)"), Statement.RETURN_GENERATED_KEYS) {
ps.setString(1, playerUUID.toString());
ps.setInt(2, punishmentBlocks);
ps.setInt(3, punishmentBlocks);
ps.setInt(4, maxExtensions);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if(rs.next())
{
int last_inserted_id = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
推荐阅读
- javascript - 是什么导致了 UI 中的角度延迟?
- webdriver - 如何将 webdriver 连接到 Android 上的 Edge 实例以运行测试脚本?
- javascript - 使用 Quokka 的 replaceAll 方法
- python - Pandas 相当于 float 或 int
- import - 在 Texthero 中导入问题
- css - Emmet 停止在 VS Code 中处理 CSS 文件
- lme4 - 线性混合模型中的异方差和序列相关性 (lmer)
- javascript - 光滑的滑块没有快速加载
- java - Java中的自定义链表
- python - 带有草莓 GraphQL 的通用容器类型