【问题标题】:Printing out Microsoft SQL data with Python onto a web page使用 Python 将 Microsoft SQL 数据打印到网页上
【发布时间】:2026-01-28 04:25:01
【问题描述】:

我需要一些帮助来弄清楚为什么我的结果只打印出表中的最后一行数据。

from flask import Flask, render_template, redirect, request

import pyodbc

#server = 'EVERETT-PC\SQLEXPRESS'
#db = 'AdventureWorks2008R2'

con = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = 'EVERETT-PC\SQLEXPRESS' , database = 'iNcentDev')

cur = con.cursor()
cur.execute("SELECT * FROM app.Currency")
s = "<table style= 'border:1px solid red'>"
for rows in cur:
    s = s + "<tr>"
for x in rows:
    s = s + "<td>" + str(x) + "</td>"
s = s + "</tr>"

con.close

app=Flask(__name__)
@app.route('/')
@app.route('/home')
def home():
  return "<html><body>" + s + "</body></html>"

if __name__=="__main__":
    app.run(debug=True)

The data I would like to print.

my results

【问题讨论】:

    标签: python sql database flask


    【解决方案1】:

    您需要使用fetchall 方法。

    rows = cur.fetchall()
    
    for row in rows:
        #....
    

    【讨论】: