需求

  1. 插入一条数据,将插入数据的自增长键值返回回来

    代码演示

  2. Java代码 ```java package com.wisdom.java;

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement;

public class TestGenerateKey { public static void main(String[] args) throws Exception{ // 注册驱动 Class.forName(“com.mysql.jdbc.Driver”);

  1. // 连接数据库
  2. String url = "jdbc:mysql://192.168.160.131:3306/subquery";
  3. Connection conn = DriverManager.getConnection(url,"root","数据库密码");
  4. // 操作数据库
  5. String sql = "insert into dept values(?,?,?)";
  6. PreparedStatement pre = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
  7. pre.setObject(1, null);
  8. pre.setObject(2, "MANAGER");
  9. pre.setObject(3, "BJ");
  10. int executeUpdate = pre.executeUpdate();
  11. // 获取插入的自增长值
  12. ResultSet generatedKeys = pre.getGeneratedKeys();
  13. if(generatedKeys.next()){
  14. System.out.println(generatedKeys.getObject(1));
  15. }
  16. // 关闭资源
  17. generatedKeys.close();
  18. pre.close();
  19. conn.close();
  20. }

}

```