Python, Sqlite3 - How to convert a list to a BLOB cell

前端 未结 5 888
梦谈多话
梦谈多话 2020-12-06 02:55

What is the most elegant method for dumping a list in python into an sqlite3 DB as binary data (i.e., a BLOB cell)?

data = [ 0, 1, 2, 3, 4, 5 ]
# now write t         


        
5条回答
  •  暖寄归人
    2020-12-06 03:17

    I have the same problem, and I'm thinking about solving this in another way.

    I think the pickle module is done exactly for something like this (serialization on python objects)

    Example (this one is for dumping to file... but I think it's easily changeble for db storage)

    Saving:

    # Save a dictionary into a pickle file.
    import pickle
    favorite_color = { "lion": "yellow", "kitty": "red" }
    pickle.dump( favorite_color, open( "save.p", "w" ) )
    

    Loading:

    # Load the dictionary back from the pickle file.
    import pickle
    favorite_color = pickle.load( open( "save.p" ) )
    

    IMHO I think this way is more elegant and safer(it works for any python object).

    That's my 2 cents

    UPDATE: After doing a bit of search on my idea, they show some gotchas on my solution ( I can't make sql searches on that field). But I still think that it's a decent solution (if you don't need to search that field.

提交回复
热议问题