Javamysql自增ID
时间: 2023-11-26 08:04:25 浏览: 70
在 MySQL 中,可以使用 AUTO_INCREMENT 关键字来为表中的一个字段设置自增长。例如,假设我们有一个名为 `users` 的表,其中包含 `id` 和 `name` 两个字段,我们可以像下面这样创建这个表:
```sql
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50)
);
```
在上面的示例中,`id` 字段被设置为自增长,因此在插入新数据时,MySQL 会自动为其赋值。
如果要在 Java 中插入数据并获取自增长的 ID,可以使用 `getGeneratedKeys()` 方法。例如:
```java
String sql = "INSERT INTO users(name) VALUES(?)";
PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
statement.setString(1, "John");
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
long id = generatedKeys.getLong(1);
System.out.println("Inserted record with ID: " + id);
}
```
在上面的示例中,我们使用 `Statement.RETURN_GENERATED_KEYS` 参数来告诉 `prepareStatement()` 方法返回生成的键。然后,我们执行 `executeUpdate()` 方法来插入数据,最后使用 `getGeneratedKeys()` 方法获取生成的键结果集,并从中获取自增长的 ID。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)