首页 > MySQL-python的DictCursor没有用?

MySQL-python的DictCursor没有用?

在设置cursor的时候按照网上说的,
cur = conn.cursor(MySQLdb.cursors.DictCursor)
据说查询的返回值会变成字典格式,但是我试了一下依然返回tuple。
用的是OSX,python 2.7
没有任何报错。


还是有用的,可以通过字段名称来获取对应的值。


用的方法不对。你看一下MySQLdb下面的cursors模块,DictCursor的这个功能是继承于CursorDictRowsMixIn,这个MixIn提供了3个额外的方法: fetchoneDict、fetchmanyDict、fetchallDict。

>>> import MySQLdb
>>> c = MySQLdb.connect('127.0.0.1', 'root', 'password', 'test')
>>> x = c.cursor(MySQLdb.cursors.DictCursor)
>>> x.execute('select * from user')
2L
>>> x.fetchoneDict()
{'age': 26L, 'id': 1L, 'name': 'test'}
【热门文章】
【热门文章】