Saving Lists as BLOB

Skip Montanaro skip at
Wed Jun 4 20:38:17 CEST 2003

    John> Is there any way to save a Python List (or Dictionary) as a binary
    John> field in MySQLdb?

    John> I have tried :

       CR.execute("UPDATE STDPAGE SET content_s = %s,fldlist = %s"
                  " where name = 'DATAENTRY'", (pagout,flds) )

    John> where flds is a python list and I get an sql error.  I dont want
    John> to convert the list to a string which would work.

You could pickle your list (or dictionary):

    CR.execute("UPDATE STDPAGE SET content_s = %s,fldlist = %s"
               " where name = 'DATAENTRY'", (pagout,pickle.dumps(flds)))

That converts it to a string, but in a more robust way than str() or repr()
would.  Upon load from the database you just pickle.loads() what's

Note that cPickle will be faster, especially if you use the binary format.
See the libref section for the pickle and cPickle module for details.


More information about the Python-list mailing list