要在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數據。