Get json results from mysql with python

This is just simple trick to retrieve data from mysql rows and turn into json.

#!/usr/bin/env python
import MySQLdb as mdb
import sys

con = mdb.connect('localhost', 'root', 'pass123', 'mydb1', charset='utf8')
cur = con.cursor(mdb.cursors.DictCursor)

def get_post():
    list = []
    gw = {}
    cur.execute("select * from tbl1_core")
    rows = cur.fetchall()
    for i in rows:
        tes = []
        # we want to fetch row to store in results
        gw["content"] = i["content"]
        tes.append(gw)
        list.append(tes)
        tes = []
        gw = {}
    return list
tes = get_post()
print tes

Leave a Comment