微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python / SQLite将列表存储为二进制文件(blob)

sqlite的官方文档建议将列表存储为二进制对象. Google引导我提出各种建议.一种是使用数组模块(array.array(‘B’,my_list2),但这不适用于非平凡的列表:

my_list2 = [(23,"Bob"), (22,"Alice")]
array.array('B',my_list2)

TypeError: an integer is required

一个建议涉及使用泡菜,但是有人插话声称它不安全.最后的建议是为每个列表变量创建一个新表,其中有几个.不过,我不愿意制定复杂的架构.

我该怎么办?如何将my_list2和其他列表一起存储在数据库中?

编辑

找到了一个优雅整洁的解决方案,该解决方案使用最少的代码即可处理简单和复杂的案例:

import json
my_list2 = [(23,"Bob Baker"), (22,"Alice Adams")]
my_list2_str = json.dumps(my_list2)
print type(my_list2_str)
 <type 'str'>
list2 = json.loads(my_list2_str)
print list2, type(list2)
 [(23, u"Bob Baker"), (22, u"Alice Adams")] <type 'list'>

解决方法:

这个问题似乎与this earlier SO question非常相似,因此起初我认为这可能会解决您的问题.但是再看一次您的问题,似乎您确实读过这个问题,因为您提到了他们提出的两种方法.另外,由于您的数据类型是不同的(元组列表而不是整数列表),我将给您一个通行证.

做一些研究,我发现很多使用sqlite3.Binary()方法(例如here)的代码示例.这可能是您想要的,但令我担心的是,我在Sqlite3 Python Interface API中找不到该功能的任何文档.因此,我建议您不要使用它.我猜想此方法已被弃用,但是我找不到任何替代它的清晰文档.

就是说,如果您阅读Sqlite3 Python Interface API,则会看到它自动将BLOB转换为python buffer对象(并将缓冲区对象转换为BLOB).因此在我看来,如果可以将列表转换为缓冲区,则可以将其简单地存储为BLOB.

在我的研究中,我发现列表不能存储为缓冲区.我还发现,虽然有将列表转换为缓冲区的方法,但它们需要简单类型的列表(即不是元组).因此,我认为最好的选择是定义一些实用程序方法,用于将列表与字符串进行相互转换,然后将字符串转换为缓冲区(从数据库检索字符串时又返回缓冲区).

def myListToStr(myList):
    """This method takes a list of (int, str) tuples and converts them to a string"""

    strList = ""
    for item in myList:
        num, name = item #split the tuple

        strList += "{}:{} ".format(num, name) #append the tuple in "num:name" format with a " " delimiter

    return strList[:-1] #remove the final space (unneeded)

def strToMyList(myStr):
    """This method takes a string in the format "int:str int:str int:str..."
    and converts it to a list of (int, str) tuples"""

    myList = []
    for tup in myStr.split(" "): #for each converted tuple
        numStr, name = tup.split(":") #split the tuple

        num = int(numStr) #NOTE: this will throw an error if numStr.isdigit() is False
        myList.append(num, name)

    return myList

现在,转换为缓冲区就像

my_list2Buff = buffer(myListToStr(my_list2))

然后回来…

my_list2 = strToList(str(my_list2Buff))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐