我想INSERT
在Java中使用JDBC在数据库(本例中为Microsoft SQL Server)中进行记录。同时,我想获取插入ID。如何使用JDBC API实现此目的?
如果它是自动生成的密钥,那么你可以使用Statement#getGeneratedKeys()
它。你需要Statement
使用与用于相同的名称进行调用INSERT
。首先,你需要创建Statement.RETURN_GENERATED_KEYS
用于通知JDBC驱动程序以返回键的语句。
这是一个基本示例:
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,因为我从未使用过它。
对于Oracle
,你可以在同一事务中直接在CallableStatementwith
之后调用with RETURNING
子句或SELECT CURRVAL(sequencename)
(或执行此操作的任何特定于DB的特定语法)INSERT以获取最后生成的密钥。