简体   繁体   English

使用 Python 将嵌套列表插入 mysql 数据库

[英]Insert nested list into mysql database using Python

I want to insert a nested list to mysql database.我想在 mysql 数据库中插入一个嵌套列表。

Normally, we insert a list data to mysql like this:通常,我们向 mysql 插入一个列表数据,如下所示:

list_data = ['Kate', 'apple']
sql = 'INSERT INTO table VALUES ('name', 'likes')'
cursor.execute(sql, list_data)

But if但如果

list_data = ['Kate', ['apple', 'orange', 'banana']]

or或者

list_data = ['Kate', {'food': 'apple', 'sports': 'running'}]

how can I do?我能怎么做? (I mean to save the pyhton list or dict as a string in mysql.) (我的意思是将 pyhton 列表或 dict 保存为 mysql 中的字符串。)

You can use the json.dumps function in Python, Try below code:您可以在 Python 中使用json.dumps function,试试下面的代码:

import json
list_data = ['Kate', json.dumps(['apple', 'orange', 'banana'])]
OR, list_data = ['Kate', json.dumps({'food': 'apple', 'sports': 'running'})]
sql = 'INSERT INTO table VALUES ('name', 'likes')'
cursor.execute(sql, list_data)

Flattening your data is also a great idea but that totally depends on your DB design and requirement.扁平化数据也是一个好主意,但这完全取决于您的数据库设计和要求。

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM