Python中让MySQL查询结果返回字典类型的方法

yipeiwu_com6年前Python基础

Python的MySQLdb模块是Python连接MySQL的一个模块,默认查询结果返回是tuple类型,只能通过0,1..等索引下标访问数据
默认连接数据库:

复制代码 代码如下:

MySQLdb.connect(
    host=host,
        user=user,
        passwd=passwd,
        db=db,
        port=port,
        charset='utf8'
)

查询数据:
复制代码 代码如下:

cur = conn.cursor()
cur.execute('select b_id from blog limit 1')
data = cur.fetchall() 
cur.close()
conn.close()

打印:
复制代码 代码如下:

for row in data:
    print type(row)
    print row

执行结果:
复制代码 代码如下:

<type 'tuple'>
(1L,)

为tuple类型。
我们可以这么干使得数据查询结果返回字典类型,即 字段=数据
导入模块
复制代码 代码如下:

import MySQLdb.cursors

在连接函数里加上这个参数  cursorclass = MySQLdb.cursors.DictCursor 如:
复制代码 代码如下:

MySQLdb.connect(
    host=host,
        user=user,
        passwd=passwd,
        db=db,
        port=port,
        charset='utf8',
    cursorclass = MySQLdb.cursors.DictCursor
)

再重新运行脚本,看看执行结果:
复制代码 代码如下:

<type 'dict'>
{'b_id': 1L}

搞定!
注意,在连接的时候port如果要指定则值必须是整型,否则会出错!

相关文章

python如何实现代码检查

前言 通常我们的python代码都是遵循PEP8的规范化格式,目的是为了保持代码的一致性、可读性。,这里给大家推荐几个常用的静态代码检查工具,大家可以酌情选择使用 1. pylint...

Python栈类实例分析

本文实例讲述了python栈类。分享给大家供大家参考。具体如下: class Path: #a list used like a stack def __init__(sel...

Pytorch 搭建分类回归神经网络并用GPU进行加速的例子

Pytorch 搭建分类回归神经网络并用GPU进行加速的例子

分类网络 import torch import torch.nn.functional as F from torch.autograd import Variable impor...

浅谈python中截取字符函数strip,lstrip,rstrip

浅谈python中截取字符函数strip,lstrip,rstrip

一、起因 今天在做角色控制中,有一个地方用到rstrip,判断用户请求的url是否与数据库对应可用权限中url相符。 if request.path == x.url or reques...

浅谈python为什么不需要三目运算符和switch

对于三目运算符(ternary operator),python可以用conditional expressions来替代 如对于x<5?1:0可以用下面的方式来实现...