首页 > 解决方案 > 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返回插入行的特定值?

标签: javasql

解决方案


您可以按照以下链接中的说明进行操作:

如何使用preparedstatement获取最后插入行的id?

您的代码可能是:

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();
        }

    }

推荐阅读