python操作json到mysql_使用Python代码将数据从JSON文件导入mysql

如何从Python中给定的JSON文件 import data into mysql ?我收到错误了

回溯(最近一次调用最后一次):文件“C:/Users/risha/PycharmProjects/Test/JSON_TEST.py”,第24行,con = pymysql.connect(host ='127.0.0.1',user ='root' ,passwd ='',db ='test',port ='3306')文件“C:\ Users \ risha \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ pymysql__init __ . py”,第90行,在连接返回连接(* args,** kwargs)文件“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行,在connect 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值