Python oracledb查询结果转字典:如何将元组转为字段名键值对
实现Oracle查询结果转字典格式
oracledb完全支持将查询结果转换为以字段名为键的字典格式,以下是两种实用方法:
方法1:手动构造字典(利用cursor.description获取字段名)
cursor.description会返回查询结果中每个字段的元组信息,其中第一个元素就是字段名称。我们可以将每行元组与字段名配对生成字典:
"""Function which connect to oracle DB""" import oracledb connection = oracledb.connect(user='login', password=userpwd, dsn=dsn) if connection.is_healthy(): print("Connection to db successful") else: print("DB Connection failed...") with connection.cursor() as cursor: cursor.execute("select * from my_SQL_view") # 提取所有字段名 column_names = [col[0] for col in cursor.description] # 遍历结果并转换为字典 for row in cursor: row_dict = dict(zip(column_names, row)) print(row_dict) # 后续可通过 row_dict['字段名'] 直接调用对应值
方法2:设置cursor.rowfactory自动返回字典
通过给cursor的rowfactory属性赋值,让查询结果直接以字典格式返回,无需手动转换:
"""Function which connect to oracle DB""" import oracledb connection = oracledb.connect(user='login', password=userpwd, dsn=dsn) if connection.is_healthy(): print("Connection to db successful") else: print("DB Connection failed...") with connection.cursor() as cursor: # 设置rowfactory,让每行结果自动转为字典 cursor.rowfactory = lambda *args: dict(zip([d[0] for d in cursor.description], args)) cursor.execute("select * from my_SQL_view") # 直接遍历得到字典格式的结果 for row_dict in cursor: print(row_dict) # 例如用 row_dict['USER_NAME'] 获取对应字段值
注:connection.is_healthy()本身返回布尔值,无需额外与== True做比较,代码中已做简化调整。
内容的提问来源于stack exchange,提问作者Stinkypoop
相关产品推荐
相关产品推荐

