我怎样才能连接blob?

时间:2017-08-10 09:42:22

标签: python sqlite group-by buffer blob

当使用GROUP BY时,有没有办法在sqlite中聚合两个记录的BLOB(二进制)。

已经尝试过没有成功:

1)来自sqlite文档的GROUP_CONCAT函数,但它不适用于BLOB数据类型,即使2个BLOB大于该字节,它也只返回1个字节。

 SELECT id, GROUP_CONCAT(blob_col)
 FROM table
 GROUP BY id

2)通过Python Sqlite3定义自己的SQL函数" create_aggregate"功能

import sqlite3

class BlobConcat:

    def __init__(self):
        self.count = buffer("")

    def step(self, value):
        print str(value)
        self.count += value[:]

    def finalize(self):
        return self.count

con = sqlite3.connect(dbPath)

con.create_aggregate("BLOB_CONCAT", 1, BlobConcat)

sql = """SELECT id, BLOB_CONCAT(blob_col)
         FROM table
         GROUP BY id"""

也只返回1个字节。

1 个答案:

答案 0 :(得分:1)

SQLite没有连接blob的内置机制。

可以编写用户定义的函数(聚合与否)来执行此操作。 您的类的问题是return self.count返回一个str对象,该对象被解释为字符串,而不是blob。您必须将其显式转换为缓冲区:

class BlobConcat:
    ...
    def finalize(self):
        return buffer(self.count)