Home > Database > Mysql Tutorial > Python将JSON格式数据转换为SQL语句以便导入MySQL数据库_MySQL

Python将JSON格式数据转换为SQL语句以便导入MySQL数据库_MySQL

WBOY
Release: 2016-06-01 13:17:03
Original
1626 people have browsed it

JSONpython

        前文中我们把网络爬虫爬取的数据保存为JSON格式,但为了能够更方便地处理数据,我们希望把这些数据导入到MySQL数据库中。phpMyadmin可以把MySQL数据库中的数据导出为JSON格式文件,但却不能把JSON格式文件导入到MySQL数据库。为了实现这个目标,可以编写Python脚本将JSON格式数据转换为SQL语句以便导入MySQL数据库。

JSON文件tencent.json部分内容:

{"recruitNumber": "1", "name": "SD10-FPS俄语游戏海外PM(深圳)", "detailLink": "http://hr.tencent.com/position_detail.php?id=9587&keywords=&tid=0&lid=0", "publishTime": "2013-11-13", "catalog": "产品/项目类", "workLocation": "深圳"}
{"recruitNumber": "2", "name": "HY2-互动娱乐游戏网游财产安全运营专员(深圳)", "detailLink": "http://hr.tencent.com/position_detail.php?id=9482&keywords=&tid=0&lid=0", "publishTime": "2013-11-28", "catalog": "产品/项目类", "workLocation": "深圳"}

在phpMyadmin中创建数据库及表结构:

CREATE DATABASE itzhaopin;
Copy after login
CREATE TABLE IF NOT EXISTS `tencent` (`id` int(11) NOT NULL auto_increment,`name` varchar(512)default NULL,`catalog` varchar(64) default NULL,`workLocation` varchar(64) default NULL,`recruitNumber` varchar(64) default NULL,`detailLink` varchar(1024) default NULL,`publishTime` varchar(64) default NULL,PRIMARY KEY (`ID`)) ENGINE=MyISAMDEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Copy after login
编写Python脚本json2sql.py将JSON格式数据转换为SQL语句:
#-*- coding: UTF-8 -*-import jsondata = []with open('itzhaopin/tencent.json') as f:	for line in f:		data.append(json.loads(line))#print json.dumps(data, ensure_ascii=False)str = "/r/n"for item in data:	#print json.dumps(item)	str = str + "insert into tencent(name,catalog,workLocation,recruitNumber,detailLink,publishTime) values "	str = str + "('%s','%s','%s','%s','%s','%s');/r/n" % (item['name'],item['catalog'],item['workLocation'],item['recruitNumber'],item['detailLink'],item['publishTime'])import codecsfile_object = codecs.open('tencent.sql', 'w' ,"utf-8")file_object.write(str)file_object.close()print "success"
Copy after login

执行该python脚本,在当前目录下将生成一个名为tencent.sql的文件,在phpMyadmin中导入并执行该文件,爬虫抓取的数据将导入MySQL数据库。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template