useGeneratedKeys="true"
时间: 2023-10-04 08:04:19 浏览: 59
Mybatis使用useGeneratedKeys获取自增主键的方法
The attribute "useGeneratedKeys" is used in JDBC (Java Database Connectivity) to indicate whether the auto-generated keys should be returned by the database when a new row is inserted into a table.
When this attribute is set to "true", the JDBC driver will request the database to return the auto-generated keys generated during the insert operation. This is useful in scenarios where the primary key or any other unique identifier for the inserted row is generated by the database itself.
For example, consider a scenario where we want to insert a new record into a table with an auto-incrementing primary key. In such a case, we can use the "useGeneratedKeys" attribute to retrieve the generated primary key value and use it for further operations.
Here's an example of how to use this attribute in JDBC:
```
String insertQuery = "INSERT INTO employee (name, age, designation) VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, "John Doe");
preparedStatement.setInt(2, 35);
preparedStatement.setString(3, "Manager");
preparedStatement.executeUpdate();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
if (resultSet.next()) {
int generatedId = resultSet.getInt(1);
System.out.println("Generated primary key: " + generatedId);
}
```
In this example, the "Statement.RETURN_GENERATED_KEYS" flag is used to indicate that we want to retrieve the auto-generated keys. After executing the insert statement, we retrieve the generated keys using the "getGeneratedKeys()" method of the PreparedStatement object. If there are any generated keys, we can retrieve them using the "getInt()" method of the ResultSet object.
阅读全文