python mysqldb使用dictcursor

python在使用MySQLdb库的时候,如下方法默认获取的cursor的结果集是tuple结构的。

con = MySQLdb.connect('host',port,'username','passwod','db_name','gbk')
 
curosr = con.cursor()
 
sql = "select * from test_table"   #test_table : name,age
 
cusor = cursor.execute(sql)
 
r = cusor.fetchone()
 
print r[0]+'\t'+r[1]
cursor.close()
 
con.close()

我们获得r的结果集是元组形式的,这样如果我们以后更改数据表的字段顺序,那么我们必须要修改现有数据库代码,如何才能做到不修改代码呢,很简单,使用DictCursor,这样得到的结果集就是字典形式的了,我们可以用key去获取数据了。

如下是如何获取DictCursor

cursor = con.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cursor.execute(sql)
r = cursor.fetchone()
print r['name']+'\t'+r['age']
posted @ 2014-02-27 21:32  anexplore  阅读(1893)  评论(0编辑  收藏  举报