zoukankan      html  css  js  c++  java
  • Python查询Mysql时返回字典结构的代码

    Python查询Mysql时返回字典结构的代码

    MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.DictCursor就行。 
    默认程序: 
    MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.DictCursor就行。默认程序:

    代码如下:

    import MySQLdb 
    db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´) 
    cursor = db.cursor() 
    cursor.execute(´select * from table´) 
    rs = cursor.fetchall() 
    print rs 


    # 返回类似如下 
    # ((1000L, 0L), (2000L, 0L), (3000L, 0L)) 
    修改后:

    代码如下:
    import MySQLdb 
    import MySQLdb.cursors 
    db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´,cursorclass = MySQLdb.cursors.DictCursor) 
    cursor = db.cursor() 
    cursor.execute(´select * from table´) 
    rs = cursor.fetchall() 
    print rs 


    # 返回类似如下 
    # ({'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 3000L}) 或者也可以用下面替换connect和cursor部分

    代码如下:

    db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´) 
    cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)

     

  • 相关阅读:
    linux常用命令笔记
    head first html与css
    多线程编程核心技术日记
    nio
    排序算法
    随笔
    数据库读写分离
    购物网站设计
    http
    servlet初始化
  • 原文地址:https://www.cnblogs.com/amengduo/p/9586355.html
Copyright © 2011-2022 走看看