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

前端 未结 5 893
梦谈多话
梦谈多话 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:13

    Assuming you want it treated as a sequence of 8-bit unsigned values, use the array module.

    a = array.array('B', data)
    >>> a.tostring()
    '\x00\x01\x02\x03\x04\x05'
    

    Use different typecodes than 'B' if you want to treat the data as different types. eg. 'b' for a sequence of signed bytes, or 'i' for a signed integer.

提交回复
热议问题