#!/usr/bin/env python3 # -*- coding: utf-8 -*- """在远程和本地数据库执行 ALTER TABLE 语句""" import paramiko import pymysql import sys import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace') HOST = "8.137.181.63" PORT = 22 USER = "root" PASSWORD = "liyanxia@6688" DB_USER = "fenleixinxi" DB_PASS = "fenleixinxi" DB_NAME = "fenleixinxi" LOCAL_DB_HOST = "127.0.0.1" LOCAL_DB_PORT = 3307 SQL = "ALTER TABLE `fa_fc_withdraw` MODIFY COLUMN `transfer_status` varchar(32) NOT NULL DEFAULT '' COMMENT 'WAIT_USER_CONFIRM/ACCEPTED/PROCESSING/SUCCESS/FAIL/CANCELLED';" def main(): print("=== [1/2] 线上数据库执行 ALTER TABLE ===") ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(HOST, port=PORT, username=USER, password=PASSWORD, timeout=20) # 1. 查看线上执行前字段定义 cmd_chk_before = f'mysql -u{DB_USER} -p{DB_PASS} {DB_NAME} -e "SHOW FULL COLUMNS FROM fa_fc_withdraw LIKE \'transfer_status\';" 2>/dev/null' _, stdout, _ = ssh.exec_command(cmd_chk_before) print("线上执行前状态:\n" + stdout.read().decode('utf-8', errors='replace').strip()) # 2. 执行 ALTER TABLE cmd_exec = f'mysql -u{DB_USER} -p{DB_PASS} {DB_NAME} -e "{SQL}" 2>/dev/null' _, stdout, stderr = ssh.exec_command(cmd_exec) err = stderr.read().decode('utf-8', errors='replace').strip() if err and "error" in err.lower(): print(f"✗ 线上执行报错: {err}") else: print("✓ 线上执行成功!") # 3. 查看线上执行后字段定义 cmd_chk_after = f'mysql -u{DB_USER} -p{DB_PASS} {DB_NAME} -e "SHOW FULL COLUMNS FROM fa_fc_withdraw LIKE \'transfer_status\';" 2>/dev/null' _, stdout, _ = ssh.exec_command(cmd_chk_after) print("\n线上执行后状态:\n" + stdout.read().decode('utf-8', errors='replace').strip()) ssh.close() print("\n=== [2/2] 本地开发数据库执行 ALTER TABLE (同步保持一致) ===") try: conn = pymysql.connect( host=LOCAL_DB_HOST, port=LOCAL_DB_PORT, user=DB_USER, password=DB_PASS, database=DB_NAME, charset="utf8mb4", autocommit=True ) with conn.cursor() as cur: cur.execute(SQL) cur.execute("SHOW FULL COLUMNS FROM fa_fc_withdraw LIKE 'transfer_status';") row = cur.fetchone() print(f"✓ 本地数据库执行成功: 字段={row[0]}, 类型={row[1]}, 注释={row[8]}") conn.close() except Exception as e: print(f"- 本地执行提示: {e}") print("\n✓ 全部执行与验证完成!") if __name__ == "__main__": main()