要在DataGrid中显示MySQL数据,你需要遵循以下步骤:
pip install mysql-connector-python
import mysql.connector
from mysql.connector import Error
try:
# 连接到MySQL数据库
connection = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
if connection.is_connected():
cursor = connection.cursor()
# 执行查询以获取数据
cursor.execute("SELECT * FROM your_table")
rows = cursor.fetchall()
print("数据已获取")
except Error as e:
print("连接失败:", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("数据库连接已关闭")
from flask import Flask, render_template
import mysql.connector
from mysql.connector import Error
app = Flask(__name__)
@app.route('/')
def index():
try:
# 连接到MySQL数据库
connection = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
if connection.is_connected():
cursor = connection.cursor()
# 执行查询以获取数据
cursor.execute("SELECT * FROM your_table")
rows = cursor.fetchall()
print("数据已获取")
except Error as e:
print("连接失败:", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("数据库连接已关闭")
return render_template('index.html', rows=rows)
if __name__ == '__main__':
app.run(debug=True)
index.html
的HTML模板文件,其中包含一个DataGrid,用于显示MySQL数据。以下是一个使用Bootstrap的简单示例:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>显示MySQL数据</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>显示MySQL数据</h1>
<table class="table table-striped">
<thead>
<tr>
<th>列1</th>
<th>列2</th>
<th>列3</th>
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
<td>{{ row[2] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
现在,当你运行Python脚本并访问Web应用程序时,你应该能在DataGrid中看到MySQL数据。