数据库
首页 > 数据库> > 存入数据库

存入数据库

作者:互联网

读取json文件的数据

with open('./jingqu/datapoi.json', 'r') as file:
    data = file.read()
    data = json.loads(data)

链接数据库

def du_sql():
    mydb = mysql.connector.connect(
        host="localhost",
        user="root",
        password="password",
        database="scence",
        auth_plugin="mysql_native_password"
    )
    dbpath = mydb.cursor()
    savaDataSql(dbpath)
    mydb.commit()

定于函数分析数据存入数据库

def savaDataSql(dbpath):
cur = dbpath
    try:
        for each in data:
            name = each['name']
            type = each['type']
            if(each['address']!=None):
                if(len(each['address'])==0):
                    address = ''
                else:
                    address = each['address']
            else:
                address = ''
            adname = each['adname']
            location = each['location']
            citycode = each['citycode']
            adcode = each['adcode']
            pname = each['pname']
            cityname = each['cityname']
            date = time.strftime("%Y-%m-%d",time.localtime())
            sql = "INSERT INTO scence1 (name,type,address,adname,location,adcode,citycode,pname,cityname,data) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
            var = (name,type,address,adname,location,adcode,citycode,pname,cityname,date)
            cur.execute(sql,var)
    except :
        print(name)

 

标签:citycode,name,数据库,address,存入,each,data,dbpath
来源: https://www.cnblogs.com/weidewozi/p/14908010.html