需求
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”);
// 连接数据库
String url = "jdbc:mysql://192.168.160.131:3306/subquery";
Connection conn = DriverManager.getConnection(url,"root","数据库密码");
// 操作数据库
String sql = "insert into dept values(?,?,?)";
PreparedStatement pre = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pre.setObject(1, null);
pre.setObject(2, "MANAGER");
pre.setObject(3, "BJ");
int executeUpdate = pre.executeUpdate();
// 获取插入的自增长值
ResultSet generatedKeys = pre.getGeneratedKeys();
if(generatedKeys.next()){
System.out.println(generatedKeys.getObject(1));
}
// 关闭资源
generatedKeys.close();
pre.close();
conn.close();
}
}
```