Python查詢Mysql時返回字典結(jié)構(gòu)的代碼
更新時間:2012年06月18日 01:16:02 作者:
MySQLdb默認(rèn)查詢結(jié)果都是返回tuple,輸出時候不是很方便,必須按照0,1這樣讀取,無意中在網(wǎng)上找到簡單的修改方法,就是傳遞一個cursors.DictCursor就行
MySQLdb默認(rèn)查詢結(jié)果都是返回tuple,輸出時候不是很方便,必須按照0,1這樣讀取,無意中在網(wǎng)上找到簡單的修改方法,就是傳遞一個cursors.DictCursor就行。
默認(rèn)程序:
MySQLdb默認(rèn)查詢結(jié)果都是返回tuple,輸出時候不是很方便,必須按照0,1這樣讀取,無意中在網(wǎng)上找到簡單的修改方法,就是傳遞一個cursors.DictCursor就行。默認(rèn)程序:
import MySQLdb
db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´)
cursor = db.cursor()
cursor.execute(´select * from table´)
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 table´)
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)
默認(rèn)程序:
MySQLdb默認(rèn)查詢結(jié)果都是返回tuple,輸出時候不是很方便,必須按照0,1這樣讀取,無意中在網(wǎng)上找到簡單的修改方法,就是傳遞一個cursors.DictCursor就行。默認(rèn)程序:
復(fù)制代碼 代碼如下:
import MySQLdb
db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´)
cursor = db.cursor()
cursor.execute(´select * from table´)
rs = cursor.fetchall()
print rs
# 返回類似如下
# ((1000L, 0L), (2000L, 0L), (3000L, 0L))
修改后:
復(fù)制代碼 代碼如下:
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 table´)
rs = cursor.fetchall()
print rs
# 返回類似如下
# ({'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 3000L}) 或者也可以用下面替換connect和cursor部分
復(fù)制代碼 代碼如下:
db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´)
cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
相關(guān)文章
解決新django中的path不能使用正則表達(dá)式的問題
今天小編就為大家分享一篇解決新django中的path不能使用正則表達(dá)式的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
python用dataframe將csv中的0值數(shù)據(jù)轉(zhuǎn)化為nan缺失值字樣
本文主要介紹了python用dataframe將csv中的0值數(shù)據(jù)轉(zhuǎn)化為nan缺失值字樣,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
解決Python pandas df 寫入excel 出現(xiàn)的問題
今天小編就為大家分享一篇解決Python pandas df 寫入excel 出現(xiàn)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
關(guān)于Python中的 oct 函數(shù)與 min 函數(shù)
本文主要介紹了Python oct 函數(shù)與 min 函數(shù);oct 函數(shù)是 Python 內(nèi)置函數(shù),主要將一個整數(shù)轉(zhuǎn)為八進(jìn)制,與 ord 函數(shù) / chr 函數(shù) 有點類似;min 函數(shù)返回給定參數(shù)的最小值,參數(shù)可以為序列語法,感興趣的小伙伴請繼續(xù)閱讀下文2021-09-09

