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中os.fork()产生子进程的例子

例1 import os print 'Process (%s) start...' %os.getpid() pid = os.fork() if pid==0: print...

pandas.DataFrame的pivot()和unstack()实现行转列

pandas.DataFrame的pivot()和unstack()实现行转列

示例:有如下表需要进行行转列: 代码如下: # -*- coding:utf-8 -*- import pandas as pd import MySQLdb from wa...

Pycharm导入Python包,模块的图文教程

Pycharm导入Python包,模块的图文教程

1、点击File->settings 2、选择Project Interpreter,点击右边绿色的加号添加包 3、输入你想添加的包名,点击Install Package 4...

opencv 获取rtsp流媒体视频的实现方法

获取实时数据 import cv2 # user: admin # pwd: 12345 # main: 主码流 # ip: 192.168.1.64 # Channels: 实时...

python 字典有序并写入json文件过程解析

python 字典有序并写入json文件过程解析

大致流程: 导包---import collections 新建一个有序字典---collections.OrderedDict() 写入json文件 代码: imp...