
JS
sqlSELECT JSON_OBJECT('id', id, 'name', name) AS JSon_dataFROM users;上述代码中,我们使用 JSON_OBJECT() 函数将 id 和 name 列的值转换为 JSON 对象,并将其命名为 JSon_data。通过执行该查询,可以得到一个包含多个 JSON 对象的结果集。案例代码:Pythonimport MySQL.connectorimport JSon# 连接到 MySQL 数据库connection = MySQL.connector.connect( host="localhost", user="root", password="password", Database="myDatabase")# 创建游标对象cursor = connection.cursor()# 执行查询语句cursor.execute("SELECT id, name, age FROM users")# 获取查询结果results = cursor.fetchall()# 将查询结果编码为 JSON 格式JSon_data = []for row in results: JSon_data.append({ 'id': row[0], 'name': row[1], 'age': row[2] })# 打印 JSON 数据print(JSon.dumps(JSon_data, indent=4))# 关闭游标和连接cursor.close()connection.close()上述代码使用 Python 的 MySQL.connector 模块连接到 MySQL 数据库,并执行了一个查询语句。然后,通过遍历查询结果,将每一行数据转换为字典,并添加到 JSon_data 列表中。最后,使用 JSon.dumps() 函数将 JSon_data 列表编码为 JSON 格式,并打印输出。JSON 编码 MySQL 结果可以简化数据传输和解析的过程,使应用程序开发更加高效和便捷。通过使用内置的 JSON 函数和 SQL 查询,我们可以轻松地将 MySQL 查询结果转换为 JSON 格式,并在不同的系统之间传输和解析数据。在实际应用中,我们可以根据具体的需求和场景,灵活运用 JSON 编码来处理 MySQL 数据。参考资料:- MySQL Documentation: JSON Functions and Operators (MySQL.com/doc/refman/8.0/en/JSon.html">https://dev.MySQL.com/doc/refman/8.0/en/JSon.html)- JSON.org: Introducing JSON (https://www.JSon.org/JSon-en.html)Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号