【问题标题】:Processing mysql result in python 3在python 3中处理mysql结果
【发布时间】:2023-04-05 00:59:02
【问题描述】:

我是这个论坛的新手,如果问题格式不是很好,请原谅。

我正在尝试从 mysql 中的数据库表中获取行并在处理 cols 后打印相同的行(其中一个 cols 包含需要扩展的 json)。以下是源和预期输出。如果有人能提出一种更简单的方法来管理这些数据,那就太好了。

注意:我已经通过大量循环和解析实现了这一点,但挑战是。
1) col_names 和 data 之间没有联系,因此当我打印数据时,我不知道结果集中数据的顺序,所以我打印的 col 标题和数据不匹配,任何方法保持同步?
2) 我希望能够灵活地更改列的顺序而无需太多返工。

实现这一目标的最佳方法是什么。没有探索过 pandas 库,因为我不确定它是否真的有必要。

使用 python 3.6

表格中的样本数据

id, student_name, personal_details, university
1, Sam, {"age":"25","DOL":"2015","Address":{"country":"Poland","city":"Warsaw"},"DegreeStatus":"Granted"},UAW
2, Michael, {"age":"24","DOL":"2016","Address":{"country":"Poland","city":"Toruń"},"DegreeStatus":"Granted"},NCU

我正在使用 MySQLdb.connect 对象查询数据库,步骤如下

query = "select * from student_details"
cur.execute(query)
res = cur.fetchall()  # get a collection of tuples 
db_fields = [z[0] for z in cur.description]  # generate list of col_names

变量中的数据:

>>>db_fields
['id', 'student_name', 'personal_details', 'university']
>>>res
((1, 'Sam', '{"age":"25","DOL":"2015","Address":{"country":"Poland","city":"Warsaw"},"DegreeStatus":"Granted"}','UAW'),
 (2, 'Michael', '{"age":"24","DOL":"2016","Address":{"country":"Poland","city":"Toruń"},"DegreeStatus":"Granted"}','NCU'))

期望的输出:

 id, student_name, age, DOL, country, city, DegreeStatus, University
 1, 'Sam', 25, 2015, 'Poland', 'Warsaw', 'Granted', 'UAW'
 2, 'Michael', 24, 2016, 'Poland', 'Toruń', 'Granted', 'NCU'

【问题讨论】:

    标签: python python-3.x mysql-python


    【解决方案1】:

    一种不太Python化但易于理解的方式(也许您可以编写一个更Python化的解决方案)可能是:

    def unwrap_dict(_input):
        res = dict()
        for k, v in _input.items():
            # Assuming you know there's only one nested level
            if isinstance(v, dict):
                for _k, _v in v.items():
                    res[_k] = _v
                continue
            res[k] = v
        return res
    
    
    all_data = list()
    for row in result:
        res = dict()
        for field, data in zip(db_fields, row):
            # Assuming you know personal_details is the only JSON column
            if field == 'personal_details':        
                data = json.loads(data)
            if isinstance(data, dict):
                extra = unwrap_dict(data)
                res.update(extra)
                continue
            res[field] = data
    
        all_data.append(res)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多