Python从数据库中读取数据,并打印表格展示数据。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#----------------------------------------------------------#
# Date    : xxxx-xx-xx                                     #
# Author  : Created by zhouwanchun.                        #
# Wechat  : lovemysql3306                                  #
# Function: This scripts function is ...                   #
# Version : 1.1                                            #
#----------------------------------------------------------#

### Python从数据库中读取数据,并打印表格展示数据。
# 导入模块
import os
import subprocess
import mysql.connector
import myloginpath
import prettytable as pt

# Linux终端清屏
os.system('clear')

# 注释信息
print("""33[1;36m
############################################################
# Date    : 2020-05-22                                     #
# Author  : Created by zhouwanchun.                        #
# Wechat  : lovemysql3306                                  #
# Function: This scripts function is ...                   #
# Version : v1.1                                           #
############################################################
33[0m""")

# 连接数据库
mylogin = myloginpath.parse('rds_dba')
# print(mylogin, type(mylogin))
conn = mysql.connector.connect(**mylogin)

# 创建SQL命令通道
sql_cmd = conn.cursor()

# SQL语句
### 检查实例参数
sql1 = "select user,host from mysql.user;"

sql_cmd.execute(sql1)
sql1_result = sql_cmd.fetchall()

# 设置列头 tb.field_names = ['user', 'host']
# 添加行 tb.add_row(['1', 'xx', 'yy'])
# 添加列 tb.add_column('status', [1, 1, 1])
# 设置对其方式:l左对齐,r右对齐,c居中(不设置默认是居中对齐)
tb = pt.PrettyTable()
tb.field_names = ['user', 'host']
tb.align['user'] = 'l'
tb.align['host'] = 'l'
for i in sql1_result:
    tb.add_row(list(i))
print("33[1;32m查看MySQL账号名33[0m")
print(tb)

sql_cmd.close()
conn.commit()
conn.close()

原文地址:https://www.cnblogs.com/zhouwanchun/p/13038680.html