MySQLdb預設查詢結果都是返回tuple,輸出時候不是很方便,必須按照0,1這樣讀取,無意中在網上找到簡單的修改方法,就是傳遞一個cursors.DictCursor就行。
預設程式:
import MySQLdb db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test') cursor = db.cursor() cursor.execute('select * from user') rs = cursor.fetchall() print rs
|
# 返回類似如下
# ((1000L, 0L), (2000L, 0L), (3000L, 0L))修改後:
import MySQLdb import MySQLdb.cursors db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db ='test',cursorclass = MySQLdb.cursors.DictCursor) cursor = db.cursor() cursor.execute('select * from user') rs = cursor.fetchall() print rs
|
# 返回類似如下
# ({'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 3000L})
或者也可以用下面替換connect和cursor部分
db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test') cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
|