Wednesday, May 20, 2009

Python and MySQL technique - Render JSON ouput based on MySQLdb to MySQL

[Updated]
After long search on how to retrieve autokey after insert new record, I found two solution for rendering JSON output and auto increment key.

##modified the following [cursorclass] , the API can render JSON style output
import MySQLdb.cursors
db = MySQLdb.connect(host='xx', user='xx', passwd='xx', db='xx',cursorclass=MySQLdb.cursors.DictCursor)
##this is for retrieving auto increment key after insert a new record
autoID= cursor.lastrowid

-----------------
[old] Not necessary to do this now, but these codes still provide examples for writing python and MySQLdb api

Here is an example for rendering JSON output based on MySQL and python. It requires one library MySQLdb. This code would help you execute sql query, then use column names (tableDescription = cursor.description) to render name/value pair JSON style output. In this example, I only render it with python Dic style, but I think it should be able converted to JSON text String directly.

By the way, JSON, though it is very flexiable to use with any syntax, but using ARRARY Style for the first layer of JSON output is better choice that some particular programs can iterate the results much easier. Especially, in Flex, when using JSON format as Flex data-bind, Flex only can loop JSON file with first layer Array. Otherwise, it would need extra actionscipt for converting the original data. (I am not pretty sure about this, at least based my current experience.) This should be resonable that for array and dic iteration, one is get by index and one is by key. There is a little difference. I just look up my another codes. Add the next two line, you should be able to conver dic into JSON text String.

Here is the code.
import MySQLdb
import simplejson as json
db = MySQLdb.connect(host='xxx', user='xx', passwd='xx', db='xxx')
cursor = db.cursor()
def getSQLJSON(hostName,dbName,id,pw,sql):
global db,cursor
resultArray =[]
cursor.execute(sql)
tableDescription = cursor.description
result = cursor.fetchall()
for e in result:
resultRaw ={}
columnIndex =0
for ee in e:
vcoulumnName = tableDescription [columnIndex][0]
resultRaw[coulumnName]=ee
columnIndex +=1
resultArray.append(resultRaw)
jsonResult = json.dumps(resultArray, separators=(',',':'))
return jsonResult

Labels:

0 Comments:

Post a Comment

<< Home

<