import json

import pymysql

json_rsp_file_path = "/root/rsp.json"

if __name__ == "__main__":
    json_rsp_file = open(json_rsp_file_path, 'r', encoding='utf-8')
    json_rsp_file_content = json_rsp_file.read()
    json_rsp_file.close()
    rsp_body = json.loads(json_rsp_file_content)
    records = rsp_body['records']
    db = pymysql.connect(host='39.101.194.63', port=23306,
                         user='root', passwd='passok123A', db='nfm', charset='utf8mb4')
    cursor = db.cursor()
    count = 0
    for record in records:
        count += 1
        fields = record['fields']
        item = {
            'id': count,
            'site_name': fields['site_name'],
            'latitude': fields['geo_point_2d'][0],
            'longitude': fields['geo_point_2d'][1],
            'joint_base': fields['joint_base'],
            'country': fields['country'],
            'component': fields['component'],
            'oper_stat': fields['oper_stat'],
            'state_terr': fields['state_terr'],
            'area': fields['area'],
            'perimeter': fields['perimeter'],
            'geo_point_2d': json.dumps(fields['geo_point_2d'], ensure_ascii=False),
            'geo_shape': json.dumps(fields['geo_shape'], ensure_ascii=False),
            'geometry': json.dumps(record['geometry'], ensure_ascii=False),
            'datasetid': record['datasetid'],
            'recordid': record['recordid'],
            'record_timestamp': record['record_timestamp'][:-6].replace("T", " ")
        }
        cols = []
        vals = []
        for k in item:
            v = item[k]
            cols.append(k)
            if type(v) == str:
                vals.append("'{}'".format(v))
            else:
                vals.append("{}".format(v))
        SQL_INSERT = "INSERT INTO nfm.us_base_info ({}) VALUES ({})".format(", ".join(cols), ", ".join(vals))
        print("[No. {}]".format(count))
        cursor.execute(SQL_INSERT)
    db.commit()
    db.close()
