在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("