如何在JDBC中获取插入ID? [英] How to get the insert ID in JDBC?

查看:112
本文介绍了如何在JDBC中获取插入ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望 INSERT 在Java中使用JDBC中的数据库(在我的情况下是Microsoft SQL Server)中的记录。同时,我想获取插入ID。如何使用JDBC API实现此目的?

I want to INSERT a record in a database (which is Microsoft SQL Server in my case) using JDBC in Java. At the same time, I want to obtain the insert ID. How can I achieve this using JDBC API?

推荐答案

如果是自动生成的密钥,则可以使用 Statement#getGeneratedKeys() 。您需要在与 INSERT 相同的语句上调用它。首先需要使用 Statement.RETURN_GENERATED_KEYS 通知JDBC驱动程序返回密钥。

If it is an auto generated key, then you can use Statement#getGeneratedKeys() for this. You need to call it on the same Statement as the one being used for the INSERT. You first need to create the statement using Statement.RETURN_GENERATED_KEYS to notify the JDBC driver to return the keys.

以下是一个基本示例:

public void create(User user) throws SQLException {
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL_INSERT,
                                      Statement.RETURN_GENERATED_KEYS);
    ) {
        statement.setString(1, user.getName());
        statement.setString(2, user.getPassword());
        statement.setString(3, user.getEmail());
        // ...

        int affectedRows = statement.executeUpdate();

        if (affectedRows == 0) {
            throw new SQLException("Creating user failed, no rows affected.");
        }

        try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
            if (generatedKeys.next()) {
                user.setId(generatedKeys.getLong(1));
            }
            else {
                throw new SQLException("Creating user failed, no ID obtained.");
            }
        }
    }
}

注意您是否依赖JDBC驱动程序来确定它是否有效。目前,大多数最新版本都可以使用,但如果我是正确的,Oracle JDBC驱动程序仍然有点麻烦。 MySQL和DB2已经支持它多年了。不久前PostgreSQL开始支持它。我无法评论MSSQL,因为我从未使用它。

Note that you're dependent on the JDBC driver as to whether it works. Currently, most of the last versions will work, but if I am correct, Oracle JDBC driver is still somewhat troublesome with this. MySQL and DB2 already supported it for ages. PostgreSQL started to support it not long ago. I can't comment about MSSQL as I've never used it.

对于Oracle,您可以调用 CallableStatement 使用 RETURNING 子句或 SELECT CURRVAL(sequencename)(或任何特定于DB的语法)在同一事务中 INSERT 之后获取最后生成的密钥。另请参见此答案

For Oracle, you can invoke a CallableStatement with a RETURNING clause or a SELECT CURRVAL(sequencename) (or whatever DB-specific syntax to do so) directly after the INSERT in the same transaction to obtain the last generated key. See also this answer.

这篇关于如何在JDBC中获取插入ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆