python mysqldb使用dictcursor

python在使用MySQLdb庫的時候,以下方法默認獲取的cursor的結果集是tuple結構的。python

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去獲取數據了。sql

以下是如何獲取DictCursor數據庫

cursor = con.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cursor.execute(sql)
r = cursor.fetchone()
print r['name']+'\t'+r['age']
相關文章
相關標籤/搜索