You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Perl/DBI转Python:寻找等效于fetchall_hashref()的方法

Python中类似Perl DBI fetchall_hashref()的等效方法

当然有,不同数据库驱动提供了不同的方式来实现按列名访问查询结果,以下是几种常见方案:

1. 利用数据库驱动自带的字典游标

大部分主流数据库驱动都支持返回字典格式的查询结果,无需手动转换:

SQLite(标准库sqlite3)

设置row_factory为sqlite3.Row,返回的行对象既可以按索引访问,也可以按列名访问:

import sqlite3

conn = sqlite3.connect('your_db.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()

cursor.execute("SELECT id, username FROM users")
rows = cursor.fetchall()

for row in rows:
    print(row['id'], row['username'])

PostgreSQL(psycopg2)

使用RealDictCursor,直接返回字典列表:

import psycopg2
from psycopg2.extras import RealDictCursor

conn = psycopg2.connect("dbname=your_db user=your_user")
cursor = conn.cursor(cursor_factory=RealDictCursor)

cursor.execute("SELECT id, username FROM users")
rows = cursor.fetchall()

for row in rows:
    print(row['id'], row['username'])

MySQL(mysql-connector-python)

创建游标时指定dictionary=True参数:

import mysql.connector

conn = mysql.connector.connect(user='your_user', password='your_pass', database='your_db')
cursor = conn.cursor(dictionary=True)

cursor.execute("SELECT id, username FROM users")
rows = cursor.fetchall()

for row in rows:
    print(row['id'], row['username'])

2. 手动转换为字典(通用方案)

如果不想依赖驱动特性,可以通过游标description属性获取列名,手动将结果转为字典列表:

# 以任意数据库驱动为例
cursor.execute("SELECT id, username FROM users")
# 获取列名列表
column_names = [col[0] for col in cursor.description]
# 将每行数据与列名配对成字典
rows = [dict(zip(column_names, row)) for row in cursor.fetchall()]

for row in rows:
    print(row['id'], row['username'])

内容的提问来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 05:07:38