使用Python代码从JSON文件将数据导入mysql

时间:2018-06-17 03:41:39

标签: python mysql json python-3.x

如何从Python中给定的JSON文件将数据导入mysql ?我收到错误

  
    

回溯(最近一次调用最后一次):文件" C:/Users/risha/PycharmProjects/Test/JSON_TEST.py" ;,第24行,在              con = pymysql.connect(host =' 127.0.0.1',user =' root',passwd ='',db =' test&# 39;,port =' 3306')文件     " C:\用户\ Risha天然气\应用程序数据\本地\程序\的Python \ Python36 \ lib中\站点包\ pymysql__init __ PY&#34 ;,     第90行,在Connect中         return Connection(* args,** kwargs)File" C:\ Users \ risha \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ pymysql \ connections.py",     第704行,在 init 中         self.connect()文件" C:\ Users \ risha \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ pymysql \ connections.py",     第964行,在连接中         self.host_info =" socket%s:%d" %(self.host,self.port)TypeError:%d format:需要一个数字,而不是str

  
import pymysql

import os
import json

# read JSON file which is in the next parent folder
file = 'C://Users//risha//PycharmProjects//Test//video.json'
json_data= open(file).read()
json_obj = json.loads(json_data)


# do validation and checks before insert
def validate_string(val):
   if val != None:
        if type(val) is int:
            #for x in val:
            #   print(x)
            return str(val).encode('utf-8')
        else:
            return val


# connect to MySQL
con = pymysql.connect(host = '127.0.0.1',user = 'root',passwd = '',db = 'test',port ='3306')
cursor = con.cursor()


# parse json data to SQL insert
for i, item in enumerate(json_obj):
    person = validate_string(item.get("person", None))
    year = validate_string(item.get("year", None))
    company = validate_string(item.get("company", None))

    cursor.execute("INSERT INTO testp (person,  year,   company) VALUES (%s,    %s, %s)", (person,  year,   company))
con.commit()
con.close()

0 个答案:

没有答案