JDBC 中高效获取插入 ID
在使用 JDBC 向数据库表中插入数据时,通常需要获取生成的键(或插入 ID),它标识新添加的记录。JDBC 提供了高效检索此 ID 的机制。
使用 Statement#getGeneratedKeys()
对于自动生成的键,JDBC 提供了 Statement#getGeneratedKeys()
方法。此方法在执行 INSERT 操作的同一语句上调用。要启用键的生成,必须使用 Statement.RETURN_GENERATED_KEYS
标志创建语句。
<code class="language-java">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("创建用户失败,没有影响行。"); } try (ResultSet generatedKeys = statement.getGeneratedKeys()) { if (generatedKeys.next()) { user.setId(generatedKeys.getLong(1)); } else { throw new SQLException("创建用户失败,未获得 ID。"); } } } }</code>
驱动程序兼容性
这种方法的成功取决于 JDBC 驱动程序的支持。大多数现代 JDBC 驱动程序都支持此功能,包括 MySQL、DB2 和 PostgreSQL。但是,Oracle JDBC 驱动程序在这方面可能仍然存在限制。
Oracle 的替代方法
对于 Oracle,请考虑使用带有 RETURNING 子句的 CallableStatement
或 SELECT 查询来检索最后生成的键。
<code class="language-sql">"{? = call INSERT_FUNCTION(?, ?, ?)}"</code>
占位符 ?
代表保存插入 ID 的变量。
以上是JDBC中如何高效检索插入ID?的详细内容。更多信息请关注PHP中文网其他相关文章!