为实现这些功能,可以使用以下工具和库:
- SQLAlchemy:用于SQL语法错误检测。
- sqlparse:用于SQL语句格式化。
- Flask:用于构建Web界面和处理请求。
以下是一个基本的实现方案:
1. 项目结构
flask_sql_formatter/
│
├── app.py # Flask应用主文件
├── templates/
│ ├── index.html # 前端页面
├── static/
│ ├── main.css # 样式文件
└── requirements.txt # 依赖库
2. 安装依赖
创建requirements.txt文件,内容如下:
Flask
SQLAlchemy
sqlparse
然后安装依赖:
pip install -r requirements.txt
3. 创建Flask应用 (app.py)
from flask import Flask, render_template, request, send_file, jsonify
import sqlparse
from io import BytesIO
from sqlalchemy.sql import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import create_engine
app = Flask(__name__)
engine = create_engine('sqlite:///:memory:')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/format', methods=['POST'])
def format_sql():
sql = request.form['sql']
try:
# SQL语法错误检测
with engine.connect() as connection:
connection.execute(text(sql))
# 格式化SQL
formatted_sql = sqlparse.format(sql, reindent=True, keyword_case='upper')
return jsonify({'formatted_sql': formatted_sql})
except SQLAlchemyError as e:
return jsonify({'error': str(e)})
@app.route('/download', methods=['POST'])
def download_sql():
formatted_sql = request.form['formatted_sql']
buffer = BytesIO()
buffer.write(formatted_sql.encode('utf-8'))
buffer.seek(0)
return send_file(buffer, as_attachment=True, download_name='formatted_sql.sql', mimetype='text/sql')
if __name__ == '__main__':
app.run(debug=True)
4. 创建前端页面 (templates/index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SQL Formatter</title>
<link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}">
</head>
<body>
<h1>SQL Formatter</h1>
<form id="sqlForm">
<textarea id="sqlInput" name="sql" rows="10" cols="80" placeholder="Paste your SQL here..."></textarea>
<br>
<button type="button" onclick="formatSQL()">Format SQL</button>
<br><br>
<textarea id="formattedSqlOutput" rows="10" cols="80" readonly></textarea>
<br>
<button type="button" onclick="copyToClipboard()">Copy to Clipboard</button>
<button type="button" onclick="downloadSQL()">Download SQL</button>
</form>
<script>
async function formatSQL() {
const sql = document.getElementById('sqlInput').value;
const response = await fetch('/format', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
'sql': sql
})
});
const result = await response.json();
if (result.error) {
alert('Error: ' + result.error);
} else {
document.getElementById('formattedSqlOutput').value = result.formatted_sql;
}
}
function copyToClipboard() {
const formattedSql = document.getElementById('formattedSqlOutput');
formattedSql.select();
document.execCommand('copy');
alert('SQL copied to clipboard');
}
async function downloadSQL() {
const formattedSql = document.getElementById('formattedSqlOutput').value;
const response = await fetch('/download', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
'formatted_sql': formattedSql
})
});
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'formatted_sql.sql';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
}
</script>
</body>
</html>
5. 创建样式文件 (static/main.css)
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
font-size: 24px;
}
textarea {
width: 100%;
margin-bottom: 10px;
}
6. 运行应用
在项目根目录下运行:
python app.py
然后打开浏览器,访问http://127.0.0.1:5000/,将看到一个可以输入、格式化、复制和下载SQL语句的界面。
当前文章价值9.67元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)

评论已关闭!