Python,Sqlite3 - 如何将列表转换为 BLOB 单元格 [英] Python, Sqlite3 - How to convert a list to a BLOB cell

查看:45
本文介绍了Python,Sqlite3 - 如何将列表转换为 BLOB 单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将 python 中的列表作为二进制数据(即 BLOB 单元)转储到 sqlite3 DB 中的最优雅方法是什么?

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 this to db as binary data
# 0000 0000
# 0000 0001
# ...
# 0000 0101

推荐答案

假设您希望将其视为 8 位无符号值序列,请使用 array 模块.

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'

如果要将数据视为不同类型,请使用与 'B' 不同的类型代码.例如.'b' 表示有符号字节序列,或 'i' 表示有符号整数.

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.

这篇关于Python,Sqlite3 - 如何将列表转换为 BLOB 单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆