美文网首页
python mysqldb使用dictcursor

python mysqldb使用dictcursor

作者: yangsir001 | 来源:发表于2020-05-24 23:08 被阅读0次

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']

相关文章

网友评论

      本文标题:python mysqldb使用dictcursor

      本文链接:https://www.haomeiwen.com/subject/snwsahtx.html