MySQL性能巡检脚本分析报告

主要依赖库

mysql.connector: 用于连接和操作MySQL数据库

pandas: 数据处理和CSV导出

docx: 生成Word格式报告

datetime: 时间处理

核心函数结构

get_mysql_config() - 获取MySQL连接配置

connect_to_mysql(config) - 建立数据库连接

get_global_status(cursor) - 获取全局状态

get_global_variables(cursor) - 获取全局变量

generate_report(conn) - 生成性能报告

create_word_report(report_data, filename) - 创建Word报告

功能特性

连接管理

支持交互式输入MySQL服务器信息(IP、端口、用户名、密码)

默认连接到information_schema数据库获取系统信息

监控指标

连接数: 当前连接数与最大连接数

查询性能: 总查询数和QPS(每秒查询数)

慢查询: 慢查询总数统计

存储引擎: InnoDB缓冲池配置

临时表: 内存和磁盘临时表创建统计

日志: 日志写入请求次数

报告输出

控制台输出: 实时显示各项性能指标

Word文档: 生成格式化的性能报告

CSV文件: 支持数据持久化存储

python 复制代码
import mysql.connector
from mysql.connector import Error
import pandas as pd
from datetime import datetime
from docx import Document
from docx.shared import Pt, RGBColor
from datetime import datetime
import time
import os

def create_word_report(report_data, filename="MySQL性能报告.docx"):
    doc = Document()
    
    # 标题
    doc.add_heading('MySQL 性能巡检报告', 0)
    doc.add_paragraph(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

    # 性能指标
    doc.add_heading('📊 性能指标', level=1)
    table = doc.add_table(rows=1, cols=2)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = '指标'
    hdr_cells[1].text = '值'

    for key, value in report_data.items():
        if key != "时间":
            row_cells = table.add_row().cells
            row_cells[0].text = key
            row_cells[1].text = str(value)

    # 设置表格字体大小
    for row in table.rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                paragraph.style.font.size = Pt(11)

    # 保存文档
    doc.save(filename)
    print(f"✅ 报告已保存为: {filename}")
def get_mysql_config():
    host = input("请输入MySQL服务器IP地址: ")
    port = int(input("请输入MySQL端口号(默认3306): ") or 3306)
    user = input("请输入MySQL用户名: ")
    password = input("请输入MySQL密码: ")
    return {
        'host': host,
        'port': port,
        'user': user,
        'password': password,
        'database': 'information_schema'
    }

def connect_to_mysql(config):
    try:
        conn = mysql.connector.connect(**config)
        if conn.is_connected():
            print("✅ 成功连接到 MySQL")
            return conn
    except Error as e:
        print(f"❌ 连接失败: {e}")
        return None

def get_global_status(cursor):
    cursor.execute("SHOW GLOBAL STATUS")
    return dict(cursor.fetchall())

def get_global_variables(cursor):
    cursor.execute("SHOW GLOBAL VARIABLES")
    return dict(cursor.fetchall())

def generate_report(conn):
    cursor = conn.cursor()
    status = get_global_status(cursor)
    variables = get_global_variables(cursor)

    # 计算 QPS
    time.sleep(1)
    status_after = get_global_status(cursor)
    qps = int(status_after['Queries']) - int(status['Queries'])

    report = {
        "时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "当前连接数": status.get('Threads_connected', 'N/A'),
        "最大连接数": variables.get('max_connections', 'N/A'),
        "总查询数": status.get('Queries', 'N/A'),
        "QPS (每秒查询)": qps,
        "慢查询总数": status.get('Slow_queries', 'N/A'),
        "InnoDB 缓冲池大小": variables.get('innodb_buffer_pool_size', 'N/A'),
        "临时表在内存中创建数": status.get('Created_tmp_tables', 'N/A'),
        "临时表在磁盘中创建数": status.get('Created_tmp_disk_tables', 'N/A'),
        "日志写入次数": status.get('Innodb_log_write_requests', 'N/A')
    }

    print("\n📊 MySQL 性能报告\n")
    for key, value in report.items():
        print(f"{key}: {value}")

    # 生成 Word 报告
    create_word_report(report)

    # 可选:保存为 CSV 文件
    report_df = pd.DataFrame([report])
    report_df.to_csv("remote_mysql_performance_report.csv", mode='a', index=False,
                     header=not os.path.exists("remote_mysql_performance_report.csv"))

    cursor.close()

def main():
    config = get_mysql_config()
    conn = connect_to_mysql(config)
    if conn:
        generate_report(conn)
        conn.close()

if __name__ == "__main__":
    main()
相关推荐
Jane Chiu32 分钟前
Oracle DBMS_REDEFINITION(在线重定义)
数据库·oracle·分区表
我叫黑大帅1 小时前
MySQL 并发插入竞态问题:原子写入实践指南
后端·mysql·面试
全栈前端老曹1 小时前
【MongoDB】安全与权限管理 —— 用户认证、角色权限、SSL 加密
前端·javascript·数据库·安全·mongodb·nosql·ssl
怕孤单的草丛1 小时前
缓存管理面临的主要问题
java·数据库·缓存
我会尽全力 乐观而坚强2 小时前
MySQL零基础入门(二)
数据库·mysql·adb
kali-Myon3 小时前
某校园门禁系统高危 SQL 注入漏洞挖掘复盘
数据库·sql·安全·web安全
程序员在囧途4 小时前
likeadmin-api API 中转站怎么做统一报价?从 /pricing、/user/balance 到 task_id 回执的落地方法
运维·服务器·数据库·likeadmin-api·api中转站·token计费
龙石数据5 小时前
MySQL 全量同步到 Hive 怎么做?三步配置教程
数据库·hive·mysql·数据治理·数据中台
程序员在囧途5 小时前
likeadmin-api API 算力超市怎么做供应商切换?统一鉴权、task_id 和 callback_url 才能稳交付
java·服务器·数据库·开放api·likeadmin-api·api算力超市