You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.9 KiB
Python

6 months ago
from datetime import datetime
import logging
import time
import os
import sys
import locale
import mysql.connector
from mysql.connector import Error
# 强制系统使用UTF-8
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
locale.setlocale(locale.LC_ALL, 'C.UTF-8')
if sys.platform != 'win32':
os.environ['TZ'] = 'Asia/Shanghai'
time.tzset() # 重新加载时区配置
# 确保日志目录存在
log_dir = 'logs'
os.makedirs(log_dir, exist_ok=True)
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(f'{log_dir}/app.log', encoding='utf-8'),
logging.StreamHandler()
]
)
class CSTFormatter(logging.Formatter):
def formatTime(self, record, datefmt=None):
ct = datetime.fromtimestamp(record.created).astimezone()
if datefmt:
s = ct.strftime(datefmt)
else:
t = ct.strftime("%Y-%m-%d %H:%M:%S")
s = "%s,%03d" % (t, record.msecs)
return s
logger = logging.getLogger(__name__)
def get_table_count(db_name):
try:
# 连接到MySQL数据库
connection = mysql.connector.connect(
host='106.227.91.181',
user='root', # 替换为您的MySQL用户名
password='cuixing@HuaerdaMySQL', # 替换为您的MySQL密码
database='huaerdames_cloud'
# host= 'localhost',
# user='root', # 替换为您的MySQL用户名
# password='root', # 替换为您的MySQL密码
# database='huaerdames_cloud'
)
if connection.is_connected():
cursor = connection.cursor()
# 获取所有表名
cursor.execute(f"SHOW TABLES FROM {db_name}")
tables = cursor.fetchall()
# 统计每个表的记录数
table_counts = {}
for table in tables:
table_name = table[0]
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
count = cursor.fetchone()[0]
table_counts[table_name] = count
return table_counts
except Error as e:
logger.error(f"数据库连接错误: {e}")
return None
finally:
if connection.is_connected():
cursor.close()
connection.close()
if __name__ == '__main__':
# 统计表数量
db_name = 'huaerdames_cloud'
table_counts = get_table_count(db_name)
if table_counts:
logger.info(f"数据库 '{db_name}' 表统计:")
for table, count in table_counts.items():
logger.info(f"表名: {table}, 记录数: {count}")
logger.info(f"总表数: {len(table_counts)}")
else:
logger.warning("未能获取表统计信息")