python操作mysql数据pymysql-执行语句select查询返回值直接返回dict字典类型或者list列表,替代默认的tuple元组类型

一、返回tuple元组类型(默认)
fetchall()将结果放在二维数组里面,每一行的结果在元组里面

import pymysql
def export(table_name):
    conn =pymysql.connect(host = '118.24.3.40',
                          user = 'jxz',password='123456',
                          db='jxz',port=3306,charset = 'utf8')
    cur = conn.cursor()
    cur.execute('select * from %s'%table_name)
    print(cur.fetchall())
export('app_student')

二、返回字典类型
想返回字典格式,只需要在建立游标的时候加个参数,cursor=pymysql.cursors.DictCursor。这样每行返回的值放在字典里面,然后整体放在一个list里面。

import pymysql
def export(table_name):
    conn =pymysql.connect(host = '118.24.3.40',
                          user = 'jxz',password='123456',
                          db='jxz',port=3306,charset = 'utf8')
    cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cur.execute('select * from %s'%table_name)
    print(cur.fetchall())
export('app_student')

三、返回list类型
使用list(chain.from_iterable(elems))

from itertools import chain

sql="select elems from table"
cursor.execute(sql)
elems = cursor.fetchall()
resultlist = list(chain.from_iterable(elems))

转载

posted @ 2023-05-26 17:56  darling331  阅读(688)  评论(0编辑  收藏  举报