Permalink
Browse files

Finished

Bug when decoding non utf-8 characters
  • Loading branch information...
damienfir committed Oct 17, 2010
1 parent f4b50d7 commit 66956753e5c9f099fbe2d15bb5c9c1cdaac2c79d
Showing with 75 additions and 2 deletions.
  1. +8 −2 README
  2. +67 −0 mysql2json.py
View
10 README
@@ -1,5 +1,11 @@
# mysql2json
mysql2json
==========
Small tool to help converting a MySQL database to json
usage: mysql2json address db user pwd
usage: mysql2json address db user pwd
Depedencies
-----------
- Python 2.6
- mysql-python
View
@@ -0,0 +1,67 @@
import sys
import json
import MySQLdb
host = 'localhost'
user = 'damienfir'
pwd = 'inside'
db_name = 'damienfir_tripin'
class mysql:
def __init__(self):
self.connect()
self.tables = {}
self.json = ''
def connect(self):
db = MySQLdb.connect(host=host, user=user, passwd=pwd, db=db_name)
self.c = db.cursor()
def get_tables(self):
self.c.execute('SHOW TABLES')
for table in self.c.fetchall():
self.tables[table[0]] = []
def get_fields(self, table):
sql = 'DESCRIBE %s'
self.c.execute(sql % table)
ret = []
for row in self.c.fetchall():
ret.append(row[0])
return ret
def get_entries(self):
sql = 'SELECT %s FROM %s'
for table in self.tables.iterkeys():
cols = self.get_fields(table)
self.c.execute(sql % (','.join(cols), table))
for row in self.c.fetchall():
item = {}
for i in range(0,len(cols)):
try:
item[cols[i]] = str(row[i])
except:
print row[i]
self.tables[table].append(item)
def to_json(self):
try:
self.json = json.dumps(self.tables)
except UnicodeDecodeError as e:
print 'json error:'
print e
return self.json
def export(self):
if not self.c:
self.connect()
self.get_tables()
self.get_entries()
return self.to_json()
def main():
sql = mysql()
print sql.export()
if __name__ == '__main__':
main()

0 comments on commit 6695675

Please sign in to comment.