数据库行统计和字典导出工具Web版
项目概述
本项目是一个基于Flask框架开发的数据库行统计和字典导出工具Web应用,支持MySQL和SQL Server数据库的连接、表信息统计和数据字典导出功能。
功能特点
- 多数据库支持:同时支持MySQL和SQL Server数据库
- 表信息统计:自动统计每个表的行数和结构信息
- 数据字典导出:支持将数据库结构导出为Word格式文档
- Web界面:提供美观的网页界面,操作简单直观
- 实时反馈:显示连接状态和统计结果
技术栈
- 后端框架:Flask 3.0+
- 数据库驱动:PyMySQL(MySQL)、pyodbc(SQL Server)
- 文档生成:python-docx
- 前端:HTML5 + CSS3 + JavaScript
- 模板引擎:Jinja2
项目结构
├── app.py # Flask应用主程序
├── templates/ # HTML模板目录
│ └── index.html # 主页模板
核心功能实现
1. 数据库连接与信息获取
MySQL数据库连接
python
def get_mysql_tables(connection_string):
"""
获取MySQL数据库中所有表的信息
参数:
connection_string: 数据库连接信息字典
返回:
表信息列表,包含表名、行数、创建SQL和字段信息
"""
conn = pymysql.connect(
host=connection_string['host'],
user=connection_string['user'],
password=connection_string['password'],
database=connection_string['database'],
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
# 获取表信息...
SQL Server数据库连接
python
def get_sqlserver_tables(connection_string):
"""
获取SQL Server数据库中所有表的信息
参数:
connection_string: 数据库连接信息字典
返回:
表信息列表,包含表名、行数、创建SQL和字段信息
"""
conn_str = f"DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={connection_string['server']};DATABASE={connection_string['database']};UID={connection_string['username']};PWD={connection_string['password']}"
conn = pyodbc.connect(conn_str)
# 获取表信息...
2. 数据字典文档生成
python
def generate_word_document(tables, db_type):
"""
生成Word格式的数据库字典文档
参数:
tables: 表信息列表
db_type: 数据库类型
返回:
BytesIO对象,包含生成的Word文档内容
"""
doc = Document()
# 添加标题和文档信息
title = doc.add_heading('数据库字典', 0)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 添加每个表的信息
for table in tables:
doc.add_heading(f'表名: {table["table_name"]}', level=1)
doc.add_paragraph(f'记录数: {table["row_count"]}')
doc.add_paragraph('创建SQL:')
doc.add_paragraph(table['create_sql'], style='Code')
# 添加字段信息表格
doc.add_paragraph('字段信息:')
table_obj = doc.add_table(rows=1, cols=4)
hdr_cells = table_obj.rows[0].cells
hdr_cells[0].text = '字段名'
hdr_cells[1].text = '数据类型'
hdr_cells[2].text = '是否为空'
hdr_cells[3].text = '默认值'
# 添加字段数据行
for col in table['columns']:
row_cells = table_obj.add_row().cells
row_cells[0].text = col['Field']
row_cells[1].text = col['Type']
row_cells[2].text = col['Null']
row_cells[3].text = str(col.get('Default', ''))
3. Web路由设计
主页路由
python
@app.route('/', methods=['GET', 'POST'])
def index():
"""
主页路由处理函数
- GET请求:显示数据库连接表单
- POST请求:处理数据库连接并显示结果
"""
if request.method == 'POST':
db_type = request.form['db_type']
# 根据数据库类型获取连接信息
if db_type == 'mysql':
connection_string = {
'host': request.form['host'],
'user': request.form['user'],
'password': request.form['password'],
'database': request.form['database']
}
tables = get_mysql_tables(connection_string)
else:
connection_string = {
'server': request.form['server'],
'username': request.form['username'],
'password': request.form['password'],
'database': request.form['database']
}
tables = get_sqlserver_tables(connection_string)
# 处理结果或错误
if isinstance(tables, dict) and 'error' in tables:
return render_template('index.html', error=tables['error'])
return render_template('index.html', tables=tables, db_type=db_type)
return render_template('index.html')
文档下载路由
python
@app.route('/download', methods=['POST'])
def download():
"""
下载数据库字典文档的路由处理函数
"""
db_type = request.form['db_type']
table_data = eval(request.form['table_data'])
# 生成Word文档
buffer = generate_word_document(table_data, db_type)
# 设置文件名并发送文件
filename = f'数据库字典_{time.strftime("%Y%m%d_%H%M%S")}.docx'
return send_file(
buffer,
mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document',
as_attachment=True,
download_name=filename
)
使用说明
安装依赖
bash
pip install flask pymysql pyodbc python-docx
启动应用
bash
python app.py
应用将在 http://127.0.0.1:5000 启动。
使用流程
- 选择数据库类型:在网页上选择MySQL或SQL Server
- 填写连接信息 :
- MySQL:主机地址、用户名、密码、数据库名
- SQL Server:服务器地址、用户名、密码、数据库名
- 连接数据库:点击"连接数据库"按钮
- 查看结果:页面将显示所有表的列表和行数统计
- 导出字典:点击"下载数据库字典"按钮,将生成Word文档下载
界面设计
连接表单区域
- 数据库类型选择(MySQL/SQL Server)
- 动态显示对应数据库的连接字段
- 连接按钮和导出按钮
结果展示区域
- 表列表:显示表名和记录数
- 表详情:显示每个表的字段信息和创建SQL
- 错误提示:显示连接失败的错误信息
技术亮点
- 动态表单:根据选择的数据库类型动态显示不同的连接字段
- 错误处理:完善的异常捕获和错误提示
- 异步生成:文档生成在服务器端完成,不阻塞用户界面
- 响应式设计:网页界面支持移动端和桌面端
- 文档格式:生成的Word文档格式规范,包含完整的表结构信息
安全考虑
- 数据库连接信息通过HTTPS传输(建议在生产环境配置)
- 密码字段使用密码输入框,不显示明文
- 连接信息仅在服务器端使用,不存储到客户端
扩展建议
- 添加权限验证:增加用户登录功能,限制访问权限
- 支持更多数据库:扩展支持PostgreSQL、Oracle等数据库
- 添加定时任务:支持定时生成数据字典并发送邮件
- 添加历史记录:保存连接历史和生成的文档记录
- 添加查询功能:支持按表名搜索和过滤
总结
本工具为数据库管理员和开发人员提供了便捷的数据库信息统计和文档生成功能,通过简单的Web界面即可完成复杂的数据库操作,大大提高了工作效率。项目采用模块化设计,易于扩展和维护,可以根据实际需求进行定制开发。