上一篇                     
               
			  Python如何显示数据库行?
- 数据库
- 2025-06-24
- 2255
 在Python中显示数据库行需连接数据库并执行查询,常用库如sqlite3、pymysql或psycopg2,步骤:1.建立连接 2.创建游标 3.执行SELECT语句 4.用fetchall()获取结果集 5.遍历行数据打印,示例使用SQLite: ,“
 
 
python,import sqlite3,conn = sqlite3.connect('test.db'),cursor = conn.cursor(),cursor.execute("SELECT * FROM table"),rows = cursor.fetchall(),for row in rows:, print(row),conn.close(),“
Python如何显示行数据库内容
在Python中显示行数据库(通常指关系型数据库)的内容,需要连接数据库、执行查询并格式化输出结果,以下是详细的操作指南:
核心步骤
-  安装数据库驱动 - 根据数据库类型安装对应驱动: # MySQL pip install mysql-connector-python # PostgreSQL pip install psycopg2 # SQLite (内置无需安装) 
 
- 根据数据库类型安装对应驱动: 
-  连接数据库 import sqlite3 # SQLite示例 conn = sqlite3.connect('example.db') cursor = conn.cursor()
-  执行SQL查询 cursor.execute("SELECT * FROM users") # 查询users表所有行 rows = cursor.fetchall() # 获取全部结果
-  格式化显示结果 -  基础方式(控制台表格):  from prettytable import PrettyTable table = PrettyTable() table.field_names = [i[0] for i in cursor.description] # 获取列名 for row in rows: table.add_row(row) print(table)输出: +----+----------+-------+ | id | name | age | +----+----------+-------+ | 1 | Alice | 30 | | 2 | Bob | 25 | +----+----------+-------+
-  Pandas(数据分析友好): import pandas as pd df = pd.DataFrame(rows, columns=[col[0] for col in cursor.description]) print(df) 输出: id name age 0 1 Alice 30 1 2 Bob 25
 
-  
完整示例(MySQL)
import mysql.connector
from prettytable import PrettyTable
# 连接数据库
db = mysql.connector.connect(
    host="localhost",
    user="root",
    password="password",
    database="testdb"
)
cursor = db.cursor()
# 执行查询
cursor.execute("SELECT id, name, email FROM customers")
# 用表格显示结果
table = PrettyTable()
table.field_names = [desc[0] for desc in cursor.description]  # 动态获取列名
for row in cursor.fetchall():
    table.add_row(row)
print(table)
# 关闭连接
cursor.close()
db.close() 
关键注意事项
-  安全防护  -  禁止直接拼接SQL:防止SQL注入攻击 # 错误方式(危险!) query = f"SELECT * FROM users WHERE name = '{user_input}'" # 正确方式(参数化查询) cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))
 
-  
-  大数据分页显示 - 使用LIMIT和OFFSET分批读取:cursor.execute("SELECT * FROM large_table LIMIT 100 OFFSET 0")
 
- 使用
-  连接管理 - 始终在try/finally或with块中关闭连接:with sqlite3.connect('db.sqlite') as conn: cursor = conn.cursor() # 执行操作...
 
- 始终在
扩展场景
-  Web应用显示(Flask示例)  from flask import Flask, render_template import sqlite3 app = Flask(__name__) @app.route('/users') def show_users(): conn = sqlite3.connect('users.db') cur = conn.cursor() cur.execute("SELECT * FROM users") data = cur.fetchall() conn.close() return render_template('users.html', users=data)HTML模板( users.html):<table> <tr><th>ID</th><th>Name</th></tr> {% for id, name in users %} <tr><td>{{ id }}</td><td>{{ name }}</td></tr> {% endfor %} </table>
-  自动刷新控制台表格 import time while True: cursor.execute("SELECT * FROM realtime_data") # 清屏并重新打印表格 print(" 33c", end="") # 清屏指令 print(PrettyTable().from_db_cursor(cursor)) time.sleep(5) # 每5秒刷新
常见问题解决
- 中文乱码:连接时指定字符集 conn = mysql.connector.connect(charset="utf8mb4", ...) 
- 连接超时:增加超时参数 conn = psycopg2.connect(..., connect_timeout=10) 
- 结果为空:检查SQL语法和表名大小写(MySQL区分大小写配置)。
Python显示数据库内容的核心流程为:连接 → 查询 → 格式化输出,关键工具包括:
- 原生驱动(sqlite3/mysql.connector)
- 表格美化库(prettytable)
- 数据分析库(pandas)
引用说明:
- MySQL官方Connector文档:https://dev.mysql.com/doc/connector-python/en/
- Python DB-API标准:PEP 249
- PrettyTable源码:https://github.com/jazzband/prettytable
- OWASP SQL注入防护指南:https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
 
  
			