我想在表中添加一个空行,并在java中获取自动增量ID。我不确定为什么,但我仍然获得userId = 0。
我的java课:

public class UserProfileDao {
    private DBConnectionManager connectionManager;
    private static final String INSERT_USER = "insert into user_profile values(default)";
    private int userId;

    public UserProfileDao(DBConnectionManager connectionManager) {
        this.connectionManager = connectionManager;
        try (Connection connection = connectionManager.getConnection()) {
            try (PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USER)) {
                try (ResultSet generatedKey = preparedStatement.getGeneratedKeys()) {
                    if (generatedKey.next()) {
                        userId = generatedKey.getInt(1);
                    }
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public int getUserId() {
        return userId;
    }
}

最佳答案

您可以使用:
LASTVAL()作为当前会话中的下一个语句并获取值

关于java - 如何插入空行并获取自动增量ID?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29949868/

10-11 17:58