如何插入空行并获取自动增量ID?

时间:2015-04-29 16:49:34

标签: java psql

我想在我的表中添加一个空行,并在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;
    }
}

1 个答案:

答案 0 :(得分:0)

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