I want to insert a nested list to mysql database.
Normally, we insert a list data to mysql like this:
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 python list or dict as a string in mysql.)
Ismael Padilla
5,6065 gold badges26 silver badges37 bronze badges
1 Answer 1
You can use the json.dumps function in Python, Try below code:
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!
answered Oct 9, 2019 at 12:47
Bharat Gera
8301 gold badge5 silver badges13 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Bruce Feng
Yes, this works. It seems we have to transfer the list or dict type to string type before inserting them to mysql rather than insert directly.
Bharat Gera
When you extract the data from DB then you have to use json.loads() to convert it into Python data structure.
Bharat Gera
Please upvote it, if it helps in your case so that other would also get the benefit. Thanks!
default
list_data = ['Kate', {'food': 'apple', 'sports': 'running'}]could be transformed toinput = ["Kate", "apple", "running"], where the column names areName,Food, andSportslist_data = ['Kate', "{'food': 'apple', 'sports': 'running'}"](note the quotes around the dictionary)