首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python SQLite 讀取顯示數據:Row 工廠、CGI 輸出與 HTML 表格渲染

     編輯:更多程式設計知識

腳本模式:命令行輸出


import sqlite3 as db

conn = db.connect('test.db')
conn.row_factory = db.Row
cursor = conn.cursor()
cursor.execute('SELECT * FROM person')
for row in cursor.fetchall():
    print(f"{row['name']} | {row['age']} | {row['address']}")
conn.close()

CGI 模式:輸出 HTML 表格


#!/usr/bin/env python3
import sqlite3 as db
import sys

conn = db.connect('test.db')
conn.row_factory = db.Row
cursor = conn.cursor()
cursor.execute('SELECT * FROM person')
rows = cursor.fetchall()

sys.stdout.write('Content-Type: text/html; charset=utf-8\r\n\r\n')
sys.stdout.write('Person List')
sys.stdout.write('')
for row in rows:
    sys.stdout.write(f'')
sys.stdout.write('
NameAgeAddress
{row["name"]}{row["age"]}{row["address"]}
') conn.close()

關鍵點

  • row_factory = db.Row 使結果支持字典式訪問;
  • CGI 輸出必須先發送 HTTP 頭(含空行),再發送 HTML;
  • 生產環境建議使用模板引擎(Jinja2)分離邏輯與視圖。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved