java插入数据后返回id
时间: 2024-02-11 11:35:55 浏览: 63
可以使用Statement.RETURN_GENERATED_KEYS选项来获取插入数据后的自增主键值。
示例代码:
```java
String sql = "INSERT INTO user(name, age) VALUES('John', 25)";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
int affectedRows = pstmt.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Inserting user failed, no rows affected.");
}
try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
if (generatedKeys.next()) {
int id = generatedKeys.getInt(1);
System.out.println("Inserted user ID: " + id);
} else {
throw new SQLException("Inserting user failed, no ID obtained.");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
```
在上述示例中,使用Statement.RETURN_GENERATED_KEYS选项创建了PreparedStatement对象,并在执行插入语句后通过getGeneratedKeys()方法获取自增主键值。如果获取成功,则输出插入数据的ID值。
阅读全文