python实现连接mysql拉取数据发报告

背景:

项目每周一需要从tdsql数据库获取一周的最新运营数据工单及数据,考虑使用脚本做定时发送

功能介绍:

python连接mysql逐条执行sql语句将结果导入本地xlsx,同时通过企业微信机器人将xlsx发送到群里

1、 创建配置文件config.ini

vim config.ini

[mysql]
host = 127.0.0.1
database = mysql
user = root
port = 3306
password = 123456

[wechat]
wx_url = https://qyapi.weixin.qq.com
robot_key = 76faa519-d4af-xxxx-xxxx-xxxxxxxxxx

[user]
query = SELECT Host, User FROM mysql.user;

[all] 
query = select * from  sys.processlist;

2、代码内容 :

(密码设在代码里、之后pyinstaller -F做简单加密、安全要求高的同学可做额外处理)

import pandas as pd
import requests
from sqlalchemy import create_engine
import configparser
import os
from datetime import datetime
import urllib.parse

MYSQL_PASSWORD = "q.]^)@5jsKE#s=N."
def send_file(wx_url, robot_key, file):
    """
    使用企业微信机器人发送文件消息

    :param wx_url: 企业微信机器人基础 URL
    :param robot_key: 企业微信机器人密钥
    :param file: 待发送文件的路径
    """
    oFileUploadUrl = f'{wx_url}/cgi-bin/webhook/upload_media?key={robot_key}&type=file'
    oWX_ROBOT_URL = f'{wx_url}/cgi-bin/webhook/send?key={robot_key}'

    # 上传文件到企业微信
    with open(file, 'rb') as f:
        files = {'media': f}
        response = requests.post(oFileUploadUrl, files=files)

    json_res = response.json()
    print(f"文件上传响应: {json_res}")

    # 检查文件上传的响应是否成功
    if 'media_id' in json_res:
        media_id = json_res['media_id']
        data = {
            "msgtype": "file",
            "file": {
                "media_id": media_id
            }
        }
        headers = {'Content-Type': 'application/json'}
        response = requests.post(url=oWX_ROBOT_URL, json=data, headers=headers, timeout=300)
        print(f"发送文件响应: {response.json()}")
    else:
        print("文件上传失败,无法获取 media_id")

def query_mysql_to_excel(engine, queries, output_dir, wx_url, robot_key):
    """
    执行查询并将结果导出为 Excel 文件,然后发送到企业微信

    :param engine: SQLAlchemy 引擎对象
    :param queries: 查询字典,键为查询名称,值为 SQL 查询
    :param output_dir: 输出目录
    :param wx_url: 企业微信基础 URL
    :param robot_key: 企业微信机器人密钥
    """
    try:
        # 如果 output 目录不存在,创建它
        os.makedirs(output_dir, exist_ok=True)

        # 获取当前时间,格式为 "YYYYMMDD_HHMM"
        current_time = datetime.now().strftime("%Y%m%d_%H%M")

        # 遍历查询列表
        for name, query in queries.items():
            # 执行查询
            df = pd.read_sql(query, engine)

            # 将数据写入 Excel 文件,文件名包含查询名称和当前时间
            excel_file = os.path.join(output_dir, f"{name}_{current_time}.xlsx")
            df.to_excel(excel_file, index=False, engine='openpyxl')
            print(f"数据成功导入到 {excel_file}")

            # 发送文件到企业微信
            send_file(wx_url, robot_key, excel_file)

    except Exception as e:
        print(f"发生错误: {e}")

def read_config(config_file):
    """
    读取配置文件,获取数据库连接信息、查询语句以及企业微信信息

    :param config_file: 配置文件路径
    :return: SQLAlchemy 引擎对象、查询字典、企业微信信息
    """
    config = configparser.ConfigParser()
    config.read(config_file)

    # 读取连接信息
    host = config['mysql']['host']
    port = config.get('mysql', 'port', fallback='3306')  # 默认为 3306
    database = config['mysql']['database']
    user = config['mysql']['user']
    password = urllib.parse.quote_plus(MYSQL_PASSWORD)

    # 读取企业微信信息
    wx_url = config['wechat']['wx_url']
    robot_key = config['wechat']['robot_key']

    # 创建 SQLAlchemy 引擎
    engine = create_engine(f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}")

    # 读取查询信息
    queries = {section: config[section]['query'] for section in config.sections() if section not in ['mysql', 'wechat']}

    return engine, queries, wx_url, robot_key

def main():
    # 使用示例
    config_file = 'config.ini'
    output_dir = 'output'  # 设置输出目录为当前目录下的 output 文件夹
    engine, queries, wx_url, robot_key = read_config(config_file)
    query_mysql_to_excel(engine, queries, output_dir, wx_url, robot_key)

if __name__ == '__main__':
    main()

要通过Python连接数据库,需要使用相应的数据库驱动程序。以下是连接常见数据库的基本示例: 1. MySQL 使用PythonMySQL驱动程序 `mysql-connector-python` 来连接MySQL数据库。首先需要安装驱动程序,可以使用 `pip` 命令安装: ``` pip install mysql-connector-python ``` 连接MySQL数据库的示例代码如下: ```python import mysql.connector # 连接数据库 cnx = mysql.connector.connect(user='root', password='password', host='localhost', database='mydatabase') # 查询数据 cursor = cnx.cursor() query = ("SELECT id, name, age FROM mytable") cursor.execute(query) # 处理数据 for (id, name, age) in cursor: print("{} - {} - {}".format(id, name, age)) # 关闭连接 cursor.close() cnx.close() ``` 2. SQLite 使用Python的SQLite驱动程序 `sqlite3` 来连接SQLite数据库,这个驱动程序是Python标准库的一部分,不需要额外安装。连接SQLite数据库的示例代码如下: ```python import sqlite3 # 连接数据库 conn = sqlite3.connect('example.db') # 查询数据 cursor = conn.cursor() query = ("SELECT id, name, age FROM mytable") cursor.execute(query) # 处理数据 for (id, name, age) in cursor: print("{} - {} - {}".format(id, name, age)) # 关闭连接 cursor.close() conn.close() ``` 3. PostgreSQL 使用Python的PostgreSQL驱动程序 `psycopg2` 来连接PostgreSQL数据库。首先需要安装驱动程序,可以使用 `pip` 命令安装: ``` pip install psycopg2 ``` 连接PostgreSQL数据库的示例代码如下: ```python import psycopg2 # 连接数据库 conn = psycopg2.connect(database="mydatabase", user="myusername", password="mypassword", host="localhost", port="5432") # 查询数据 cursor = conn.cursor() query = ("SELECT id, name, age FROM mytable") cursor.execute(query) # 处理数据 for (id, name, age) in cursor: print("{} - {} - {}".format(id, name, age)) # 关闭连接 cursor.close() conn.close() ``` 以上示例代码只是演示如何连接数据库和查询数据,实际的查询语句和操作方式需要根据具体的数据库和表结构进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值