人生若只如初见

WXY

Python读取Mysql数据转成List

2023-10-10

环境: 系统linux 编辑器pycharm python版本3.11

数据库数据

2023-10-10_14-59.png

依赖

pip install mysql-connector-python

代码

import mysql.connector

# 参考 https://www.cnblogs.com/wynlfd/p/10986107.html
# 主方法
if __name__ == '__main__':

    con = mysql.connector.connect(
        host="127.0.0.1",
        port=3306,
        database="db_name",
        user="root",
        passwd="123456",
        charset='utf8'
    )

    # 链接
    cursor = con.cursor()

    # sql语句
    query = "select * from test_demo limit 2"

    # 执行
    cursor.execute(query)

    # 获取的是数据库每个栏位(字段,列)
    description = cursor.description

    # 查询全部
    resultAll = cursor.fetchall()


    def data2dict(data):
        return dict(zip([x[0] for x in description], [x for x in data]))


    news_list = list(map(data2dict, resultAll))
    print(news_list)

    # 处理数据
    for item in news_list:
        date = item.get("create_time")
        print(date)

执行结果

2023-10-10_15-01.png

参考

https://www.cnblogs.com/wynlfd/p/10986107.html