【python 问题解决】 ---- sqlite 查询数据返回的是元组,转换为字典

1. 问题

  1. python 的 sqlite 查询数据返回的是元组类型;
  2. 返回到前端就是二维数组;

1.1 效果图

1.1.1 后端打印

在这里插入图片描述

1.1.2 前端打印

在这里插入图片描述

2. 解决办法

2.1 重写连接对象的 row_factory 方法

  # 数据转字典
  def dict_factory(self, cursor, row):
    data = {}
    for idx, col in enumerate(cursor.description):
      data[col[0]] = row[idx]
    return data

  # 查询数据
  def query(self,sql):
    with self.con:
      self.con.row_factory = self.dict_factory
      self.cur = self.con.cursor()
      self.cur.execute(sql)
      rows = self.cur.fetchall()
      return rows

3. 总结

  1. 重写 row_factory 方法后,查询数据返回的就是字典!
  2. 参考:学习笔记—SQLite3基本命令

Guess you like

Origin blog.csdn.net/m0_38082783/article/details/118364128