Created
May 15, 2014 10:38
-
-
Save yasinkuyu/51312f1c1ffe9a59be8c to your computer and use it in GitHub Desktop.
Foursquare categories recursive MySQL Database insert with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @yasinkuyu | |
# 15/05/2014 | |
import json | |
import MySQLdb | |
# First dump foursquare-categories.json ----> https://gist.github.com/janosgyerik/2906942 | |
# CREATE TABLE `category` ( | |
# `CatId` int(11) NOT NULL AUTO_INCREMENT, | |
# `ParentId` int(11) DEFAULT NULL, | |
# `Name` char(255) DEFAULT NULL, | |
# `fid` varchar(255) DEFAULT NULL, | |
# PRIMARY KEY (`CatId`) | |
#) ENGINE=MyISAM AUTO_INCREMENT=8995 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; | |
# Open database connection | |
db = MySQLdb.connect("localhost", "root", "root", "dbname") | |
from pprint import pprint | |
json_data = open('foursquare-categories.json') | |
data = json.load(json_data) | |
cmd = db.cursor() | |
def recursive(item, insert_id): | |
for subitem in item['categories']: | |
cmd.execute("INSERT INTO category(`Name`, `ParentId`, `fid`) VALUES ('%s', '%d','%s')" % | |
(subitem['name'].replace("'", "`"), insert_id, subitem['id'])) | |
insert_id = db.insert_id() | |
db.commit() | |
print["---- " + subitem['name']] | |
if "categories" in subitem: | |
recursive(subitem, insert_id) | |
for item in data['categories']: | |
cmd.execute("INSERT INTO category(`Name`, `ParentId`, `fid`) VALUES ('%s', '%d','%s')" % | |
(item['name'], 0, item['id'])) | |
insert_id = db.insert_id() | |
db.commit() | |
print[item['name']] | |
recursive(item, insert_id) | |
db.close() | |
json_data.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment