Python的MySQLdb模塊是Python鏈接MySQL的一個模塊,默認查詢結果返回是tuple類型,只能經過0,1..等索引下標訪問數據
默認鏈接數據庫:
python
MySQLdb.connect( host=host, user=user, passwd=passwd, db=db, port=port, charset='utf8' )
複製代碼打印:web
複製代碼代碼以下 for row in data: print type(row) print row
執行結果:
數據庫
複製代碼函數
代碼以下: <type 'tuple'> (1L,)
爲tuple類型。
咱們能夠這麼幹使得數據查詢結果返回字典類型,即 字段=數據
導入模塊
spa
import MySQLdb.cursors
在鏈接函數里加上這個參數 cursorclass = MySQLdb.cursors.DictCursor 如:
code
MySQLdb.connect( host=host, user=user, passwd=passwd, db=db, port=port, charset='utf8', cursorclass = MySQLdb.cursors.DictCursor )
再從新運行腳本,看看執行結果:
orm
<type 'dict'> {'b_id': 1L}
搞定!
注意,在鏈接的時候port若是要指定則值必須是整型,不然會出錯!索引