存入数据库

2021/6/21 2:27:53

本文主要是介绍存入数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

读取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)

 



这篇关于存入数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程