行政区划代码(使用国务院官方数据)形成树形结构数据表

发布时间 2023-05-17 11:07:52作者: 烧肉粽

2022年中华人民共和国行政区划代码

https://www.mca.gov.cn/article/sj/xzqh/1980/202304/20230400047341.shtml

 

 下拉复制

粘贴到excel,导入数据库

表结构为:

CREATE TABLE `citynew` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pre_id` int(11) DEFAULT NULL,
`code` varchar(255) DEFAULT NULL,
`city` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3212 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

生成父级preId代码:

public void fun (boolean flag){
Map map = new HashMap();
List<Citynew> list = citynewMapper.selectAll(map);
int i = list.size();
for (int j = 0; j < i; j++) {
Citynew item = list.get(j);
if(flag){
if(item.getPreId()==null) {
if (item.getCode() != null && item.getCode().endsWith("0000")) {
item.setPreId(0);
citynewMapper.updateByPrimaryKey(item);
}
if (!item.getCode().endsWith("00") && (!item.getCode().endsWith("0000"))) {
//判断是否省直辖
String midFix = item.getCode().substring(2, 4);
if(midFix.equals("90")){
String preFix = item.getCode().substring(0, 2);
preFix = preFix + "0000";
Map params = new HashMap();
params.put("code", preFix);
Citynew privance = citynewMapper.selectAll(params).get(0);
int preId = privance.getId();
item.setPreId(preId);
citynewMapper.updateByPrimaryKey(item);
}else {
String preFix = item.getCode().substring(0, 4);
preFix = preFix + "00";
Map params = new HashMap();
params.put("code", preFix);
Citynew city = citynewMapper.selectAll(params).get(0);
int preId = city.getId();
item.setPreId(preId);
citynewMapper.updateByPrimaryKey(item);
}
}
if (item.getCode().endsWith("00") && (!item.getCode().endsWith("0000"))) {
String preFix = item.getCode().substring(0, 2);
preFix = preFix + "0000";
Map params = new HashMap();
params.put("code", preFix);
Citynew privance = citynewMapper.selectAll(params).get(0);
int preId = privance.getId();
item.setPreId(preId);
citynewMapper.updateByPrimaryKey(item);
}
}
}else {
item.setId(item.getId()+1);
citynewMapper.updateByPrimaryKey(item);
}
}
}