'''
数据库标准geom字段组成包括:type、crs、coordinate
其中,
type和coordinate与geojson文件中 feature[i].geometry中的type和coordinate一致
feature[i]. properties中“编号”字段为表链接字段
命令
ST_GeomFromGeoJSON -- json转geom
'''
# 读取数据
import json
import psycopg2
# admin_village.json ----> base_community 行政村 1
# building.json ----> base_building 楼栋
# district.json ----> base_region 行政区 1
# subdis.json ----> base_street 街道 1
# ------------------
json_file_name = 'village0812.json'
# ------------------
con = psycopg2.connect(host='', port=, database='', user='', password='')
cursor = con.cursor()
def save_to_database(g_type, g_crs, g_coordinates, g_id):
g_type = f'"type": "{g_type}"'
g_crs = f'"crs": {g_crs}'.replace("'", '"')
g_coordinates = f'"coordinates": {g_coordinates}'
geom = '{' + f"{g_type},{g_crs},{g_coordinates}" + '}'
sql = f"update public.base_village set geom = st_geomfromgeojson('{geom}') where village_no = '{g_id}' and geom is null"
# print(sql)
try:
cursor.execute(sql)
con.commit()
print('更新成功...')
except:
con.rollback()
print('更新失败.')
if __name__ == '__main__':
with open(f'{json_file_name}', 'r') as f:
data = json.load(f)
crs = data['crs']
features = data['features']
for feature in features:
geometry = feature['geometry']
g_type = geometry['type']
g_crs = crs
g_coordinates = geometry['coordinates']
g_id = feature['properties']['id']
save_to_database(g_type, g_crs, g_coordinates, g_id)