ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

使用pymysql读取mysql游标数据集------对结果集进行行列显示,并左右对齐显示

2022-01-01 20:05:17  阅读:180  来源: 互联网

标签:df 游标 pymysql tabulate mysql print 对齐 columns row


1.连接数据库,并从cursor.description中获取列名

import pymysql as mysql
import pandas as pd


def make_lalign_formatter(df, cols=None):
    """
    Construct formatter dict to left-align columns.
    Parameters
    ----------
    df : pandas.core.frame.DataFrame
        The DataFrame to format
    cols : None or iterable of strings, optional
        The columns of df to left-align. The default, cols=None, will
        left-align all the columns of dtype object
    Returns
    -------
    dict
        Formatter dictionary
    """
    if cols is None:
       cols = df.columns[df.dtypes == 'object']

    return {col: f'{{:<{df[col].str.len().max()}s}}'.format for col in cols}


# 连接MySQL数据库
host = 'localhost'
port = 3306
db = 'levis_cn_testing'
user = 'root'
password = 'root'


connection = mysql.connect(host=host, port=port, user=user, password=password, database=db, charset='utf8mb4')
cursor=connection.cursor()
sql="SELECT store_code_id, store_code,name, store_type FROM `store`  limit 10;"
cursor.execute(sql)
result = cursor.fetchall()
total_fields = len(cursor.description)
fields_names = [i[0] for i in cursor.description]
print("*************** get column name *************")
print(fields_names)
print("*************** show result with column name *************")

 

2.通过逐个读取字段,拼接的形式显示行列

print("*************** show result with column name *************")
print("%s\t %s\t%s\t%s" % (fields_names[0], fields_names[1], fields_names[2], fields_names[3]))
for row in result:
    #print(row)
    print("%d\t %s\t%s\t%s"%(row[0] ,row[1] ,row[2] ,row[3]   ) )

 

 

 

 

3.使用pandas的read_sql_query或 read_sql获取数据集,会返回一个数据表的DataFrame格式,这里调用了自定义make_lalign_formatter方法来进行对齐显示

print("*************** Print Table with column name using Pandas.Frame *************")
df = pd.read_sql_query(sql,connection)
# Left align all columns
print(df.to_string(formatters=make_lalign_formatter(df),
                   index=False,
                   justify='left'))

 

 

 

 

4.引用tabulate,使用tabulate来进行对齐显示方法来进行对齐显示,注意到这里字符串列进行了左对齐,数字列还是右对齐

print("***************使用tabulate进行对齐显示 *************")
from tabulate import tabulate
print(tabulate(df, showindex=False, headers=df.columns,stralign='left'))

 

 

 

 

 

5.关闭游标和连接

cursor.close()
connection.close()

 

标签:df,游标,pymysql,tabulate,mysql,print,对齐,columns,row
来源: https://www.cnblogs.com/noteswiki/p/15755959.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有