Reputation: 77
How can I store python 'list' values into MySQL and access it later from the same database like a normal list?
I tried storing the list as a varchar
type and it did store it. However, while accessing the data from MySQL I couldn't access the same stored value as a list, but it instead it acts as a string. So, accessing the list with index was no longer possible. Is it perhaps easier to store some data in the form of sets datatype? I see the MySQL datatype 'set' but i'm unable to use it from python. When I try to store set from python into MySQL, it throws the following error: 'MySQLConverter' object has no attribute '_set_to_mysql'.
Any help is appreciated
P.S. I have to store co-ordinate of an image within the list along with the image number. So, it is going to be in the form [1,157,421]
Upvotes: 4
Views: 7353
Reputation: 753
Are you using an ORM like SQLAlchemy?
Anyway, to answer your question directly, you can use json
or pickle
to convert your list to a string and store that. Then to get it back, you can parse it (as JSON or a pickle) and get the list back.
However, if your list is always a 3 point coordinate, I'd recommend making separate x
, y
, and z
columns in your table. You could easily write functions to store a list in the correct columns and convert the columns to a list, if you need that.
Upvotes: 2
Reputation: 5533
Use a serialization library like json
:
import json
l1 = [1,157,421]
s = json.dumps(l1)
l2 = json.loads(s)
Upvotes: 7