1.安裝pyodbc模塊:
pip install pyodbc
2.安裝sql server驅動:
https://docs.microsoft.com/zh-cn/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver15
3.編寫python代碼:
import pyodbc
# 連接數據庫
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=test;UID=sa;PWD=123456')
# 創建游標
cursor = conn.cursor()
# 執行SQL語句
cursor.execute('select * from table')
# 獲取查詢結果
rows = cursor.fetchall()
# 關閉連接
conn.close()
4.使用Flask框架編寫網頁:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', rows=rows)
if __name__ == '__main__':
app.run()
5.編寫index.html:
<html>
<head>
<title>SQL Server數據庫查詢結果</title>
</head>
<body>
<table>
<tr>
<th>字段1</th>
<th>字段2</th>
<th>字段3</th>
</tr>
{% for row in rows %}
<tr>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
<td>{{ row[2] }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>